Skip to main content

Go Syntax Cheat Sheet: Quick Reference for Developers

This cheat sheet is a concise reference for the most frequently used Go language constructs. It is designed for developers who already understand the basics and need a quick reminder, and for newcomers who want a high‑level overview of Go’s syntax. For in‑depth explanations and tutorials, follow the links to the dedicated Foundations articles.

Program Structure

Every Go program consists of packages, imports, and a main function when producing an executable.

package main

import "fmt"

func main() {
fmt.Println("Hello, Go")
}
  • The main package defines an executable.
  • import brings packages into scope.
  • func main() is the entry point.

Variables and Constants

var name string = "Go" // explicit declaration
age := 10 // short declaration (inside functions)
const Pi = 3.14159 // constant
var x, y int // multiple variables with zero values
  • Variables can be declared with var or :=.
  • := can only be used inside functions.
  • Constants are declared with const.
  • Uninitialised variables have zero values (0, "", nil, etc.).

Basic Types

TypeDescription
booltrue or false
stringimmutable sequence of bytes
intplatform‑dependent signed integer
int8int64signed integers of specific size
uintplatform‑dependent unsigned integer
uint8uint64unsigned integers of specific size
float32, float64floating‑point numbers
bytealias for uint8
runealias for int32, represents a Unicode code point
complex64, complex128complex numbers

Operators

CategoryOperators
Arithmetic+, -, *, /, %
Comparison==, !=, <, <=, >, >=
Logical&&, ||, !
Bitwise&, |, ^, &^, <<, >>
Assignment=, +=, -=, etc.

Control Flow

If

if x > 0 {
// ...
} else if x < 0 {
// ...
} else {
// ...
}

// if with a short statement
if err := doSomething(); err != nil {
return err
}

Switch

switch day {
case "Monday":
// ...
case "Tuesday", "Wednesday":
// ...
default:
// ...
}

// switch without an expression
switch {
case hour < 12:
fmt.Println("morning")
default:
fmt.Println("afternoon")
}

For (the only loop construct)

// classic for
for i := 0; i < 10; i++ {
fmt.Println(i)
}

// while-like
for condition {
// ...
}

// infinite loop
for {
break
}

// range over slices, maps, strings
for index, value := range collection {
// ...
}

Functions

// basic function
func add(a int, b int) int {
return a + b
}

// multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}

// named return values
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // naked return
}

// variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}

// anonymous function (closure)
adder := func(a, b int) int {
return a + b
}
  • Arguments of the same type can share the type declaration (a, b int).
  • Named return values are useful for documentation but should not obscure code.

Structs and Methods

type Person struct {
Name string
Age int
}

// struct literal
p := Person{Name: "Alice", Age: 30}

// method with value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}

// method with pointer receiver
func (p *Person) Birthday() {
p.Age++
}
  • Use a pointer receiver when the method needs to modify the receiver or to avoid copying large structs.
  • Keep receiver names short and consistent (e.g., p for Person).

Interfaces

type Speaker interface {
Speak() string
}

// implicit implementation: any type with Speak() string satisfies Speaker
type Dog struct{}

func (d Dog) Speak() string {
return "Woof"
}

var s Speaker = Dog{}
  • Interfaces are satisfied implicitly; no implements keyword.
  • Keep interfaces small (1–3 methods). Use the empty interface any (or interface{}) only when truly necessary.

Error Handling

// creating errors
err := errors.New("something went wrong")
err := fmt.Errorf("user %s not found", name)

// wrapping errors (Go 1.13+)
err := fmt.Errorf("failed to process: %w", originalErr)

// checking errors
if errors.Is(err, ErrNotFound) {
// handle specific error
}

var customErr *MyError
if errors.As(err, &customErr) {
// access fields of customErr
}
  • Always check errors; do not discard them with _.
  • Wrap errors with %w to preserve the original error for later inspection.

Collections

Arrays (fixed size)

var arr [3]int
arr[0] = 1
b := [2]string{"hello", "world"}

Slices (dynamic)

slice := []int{1, 2, 3}
slice = append(slice, 4)
sub := slice[1:3] // [2, 3]

// make a slice with length and capacity
s := make([]int, 5, 10)
  • Slices are references to underlying arrays. They are passed by value, but the value includes a pointer to the array, so modifications can be seen by the caller.
  • len returns the number of elements; cap returns the capacity.

Maps

m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
delete(m, "a")

value, ok := m["z"] // ok is false if key not present
if !ok {
fmt.Println("not found")
}
  • Maps are unordered. Iteration order is not guaranteed.

Strings

s := "hello"
len(s) // number of bytes
s[0] // byte at index 0 ('h')
for i, r := range s {
// r is a rune (Unicode code point)
}

Pointers

x := 42
p := &x // p is a pointer to x
fmt.Println(*p) // dereference: 42

*p = 21 // modify x through the pointer
  • Go has no pointer arithmetic.
  • Use pointers to share data and to allow functions to modify values.

Packages and Modules

// package declaration at the top of each file
package mypackage

// exported identifiers start with uppercase
func PublicFunc() {}
var PublicVar int

// unexported (private) identifiers start with lowercase
func privateFunc() {}
  • A module is defined by a go.mod file.
  • The module path (example.com/myapp) is the import prefix for all its packages.
  • go.sum records cryptographic hashes of dependencies for integrity.

Common Built‑in Functions

FunctionPurpose
lenlength of string, slice, array, map, or channel
capcapacity of slice, array, or channel
makeallocate and initialise slice, map, or channel
newallocate zeroed memory and return a pointer
appendadd elements to a slice
copycopy elements from one slice to another
deleteremove an entry from a map
closeclose a channel
panicabort normal execution with an error
recoverregain control after a panic (used in deferred functions)

Frequently Used Standard Library Packages

PackagePurpose
fmtformatted I/O (print, scan, sprintf)
stringsstring manipulation (split, join, replace)
bytesbyte slice operations similar to strings
errorserror creation and inspection
ioI/O primitives (Reader, Writer)
osoperating system functionality
timedate, time, and duration
contextrequest‑scoped values, deadlines, cancellation
syncmutex, waitgroup, once
encoding/jsonJSON marshalling and unmarshalling
net/httpHTTP client and server

Common Go Commands

CommandPurpose
go run .compile and run the package in the current dir
go buildcompile the package and produce a binary
go test ./...run all tests in the module
go fmt ./...format all source files
go vet ./...run static analysis
go mod tidyadd missing and remove unused dependencies
go mod downloaddownload module dependencies
go versionprint the installed Go version
go envprint Go environment variables

Best Practices

  • Write simple, explicit code; avoid cleverness.
  • Always check and handle errors.
  • Prefer composition (embedding) over inheritance.
  • Define interfaces where they are used, not where they are implemented.
  • Keep interfaces small (1–3 methods).
  • Run gofmt (or go fmt) before committing.
  • Use Go Modules for dependency management in every project.
  • Follow naming conventions: MixedCaps for exported names, mixedCaps for unexported.

Deepen your understanding with the full Foundations articles: