elefcode
← All cheat sheets

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 declaration
const Pi = 3.14Constant
int int64 float64 string bool byte runeCommon built-in types
float64(x)Type conversion — always explicit
Zero values: 0, "", false, nilWhat uninitialised variables hold

Slices and maps

xs := []int{1, 2, 3}Slice literal
xs = append(xs, 4)Append — always reassign the result
xs[1:3]Sub-slice (shares the underlying array)
make([]int, 0, 10)Slice with length 0 and capacity 10
m := map[string]int{"a": 1}Map literal
v, ok := m["k"]Look up and check whether the key exists
delete(m, "k")Remove a key

Control flow

for i := 0; i < n; i++ { }Classic loop
for i, v := range xs { }Iterate a slice, map, string, or channel
for i := range 10 { }Loop 0–9 (Go 1.22+)
for cond { }While loop
if v, err := f(); err != nil { }If with an init statement
switch x { case 1, 2: ... default: ... }Switch — no fallthrough by default
defer f.Close()Run when the surrounding function returns

Functions and errors

func add(a, b int) int { }Function with typed parameters
func f() (int, error) { }Multiple return values
if err != nil { return err }The standard error check
fmt.Errorf("load: %w", err)Wrap an error with context
errors.Is(err, os.ErrNotExist)Check for a wrapped error
func sum(nums ...int) intVariadic function

Structs and interfaces

type User struct { Name string `json:"name"` }Struct with a JSON tag
func (u *User) Rename(n string) { }Method with a pointer receiver
type Shape interface { Area() float64 }Interface — satisfied implicitly
v, ok := x.(string)Type assertion
func Map[T, U any](xs []T, f func(T) U) []UGeneric function

Concurrency and the go tool

go f()Start a goroutine
ch := make(chan int); ch <- 1; v := <-chCreate, send on, and receive from a channel
select { case v := <-ch: ... }Wait on several channel operations
var wg sync.WaitGroupWait for a group of goroutines
go mod init example.com/appStart a module
go run . / go build / go test ./...Run, build, and test
go fmt ./... / go vet ./...Format code / report suspicious constructs

Related guides

More cheat sheets