Languages
Go Cheat Sheet — Syntax and Standard Library Reference
Go is small on purpose. This sheet covers nearly all of the everyday syntax, plus the go command and the concurrency basics.
Put it into practice with the matching tool.
Generate Go structs from JSON →Advertisement
Variables and types
x := 42Declare and infer type (inside functions)var name string = "Ana"Explicit declarationconst Pi = 3.14Constantint int64 float64 string bool byte runeCommon built-in typesfloat64(x)Type conversion — always explicitZero values: 0, "", false, nilWhat uninitialised variables holdSlices and maps
xs := []int{1, 2, 3}Slice literalxs = append(xs, 4)Append — always reassign the resultxs[1:3]Sub-slice (shares the underlying array)make([]int, 0, 10)Slice with length 0 and capacity 10m := map[string]int{"a": 1}Map literalv, ok := m["k"]Look up and check whether the key existsdelete(m, "k")Remove a keyControl flow
for i := 0; i < n; i++ { }Classic loopfor i, v := range xs { }Iterate a slice, map, string, or channelfor i := range 10 { }Loop 0–9 (Go 1.22+)for cond { }While loopif v, err := f(); err != nil { }If with an init statementswitch x { case 1, 2: ... default: ... }Switch — no fallthrough by defaultdefer f.Close()Run when the surrounding function returnsFunctions and errors
func add(a, b int) int { }Function with typed parametersfunc f() (int, error) { }Multiple return valuesif err != nil { return err }The standard error checkfmt.Errorf("load: %w", err)Wrap an error with contexterrors.Is(err, os.ErrNotExist)Check for a wrapped errorfunc sum(nums ...int) intVariadic functionStructs and interfaces
type User struct { Name string `json:"name"` }Struct with a JSON tagfunc (u *User) Rename(n string) { }Method with a pointer receivertype Shape interface { Area() float64 }Interface — satisfied implicitlyv, ok := x.(string)Type assertionfunc Map[T, U any](xs []T, f func(T) U) []UGeneric functionConcurrency and the go tool
go f()Start a goroutinech := make(chan int); ch <- 1; v := <-chCreate, send on, and receive from a channelselect { case v := <-ch: ... }Wait on several channel operationsvar wg sync.WaitGroupWait for a group of goroutinesgo mod init example.com/appStart a modulego run . / go build / go test ./...Run, build, and testgo fmt ./... / go vet ./...Format code / report suspicious constructs