GoGo

Go cheatsheet – syntax overview

90 key commands and patterns for quick reference.

Basics Types, conversion & operators Control flow Functions Slices, arrays & maps Strings Structs & interfaces Errors & panic Concurrency go tool

Basics

fmt.Println("Text", x)Print with a line break
fmt.Printf("%s %d %.2f\n", s, n, f)Formatted output
s := fmt.Sprintf("%05d", 42)Format and return as a string
// Comment /* Block */Comments
x := 42Short declaration with type inference
var x int = 5Declaration with a type (also at package level)
const Pi = 3.14159Constant
x, y = y, xSwap values

Types, conversion & operators

int int64 float64 string bool byte runeMost important basic types
float64(x) int(f) string(r)Explicit conversion (int(3.9) = 3)
n, err := strconv.Atoi("42")String to int (with error)
s := strconv.Itoa(42)int to string
f, err := strconv.ParseFloat("2.5", 64)String to float64
b, err := strconv.ParseBool("true")String to bool
fmt.Printf("%T", x)Print the type of a value
var p *int p = &x *p = 3Declare a pointer, take an address, dereference
+ - * / %Arithmetic (int / int = int)
== != < > <= >=Comparisons
&& || !Logical operators
x++ x-- x += 2Increment (statement only), compound assignment
& | ^ << >>Bitwise operations
ch <- v v := <-chSend to / receive from a channel

Control flow

if x > 0 { } else if x == 0 { } else { }Branching (without parentheses)
if v, err := f(); err != nil { }if with a preceding statement
for i := 0; i < 5; i++ { }Counting loop
for i := range 5 { }Loop 0..4 (Go 1.22+)
for i, v := range s { }Index and value over slice/array/string
for cond { } for { }While loop / infinite loop
switch x { case 1, 2: default: }switch (no break, multiple values per case)
break continue gotoExit loop / next iteration / jump

Functions

func f(a, b int) int { return a + b }Function with parameters and return value
func f() (int, error)Multiple return values
func f(xs ...int) f(s...)Variadic / unpack a slice
func f() (lo, hi int) { return }Named return values
func(x int) int { return x * 2 }Anonymous function (closure)
defer f.Close()Postpone a call until the function ends
func Name() {} func name() {}Exported (uppercase) / package-private (lowercase)

Slices, arrays & maps

s := []int{1, 2, 3} a := [3]int{1, 2, 3}Slice / array
s = append(s, 4, 5) s = append(s, t...)Append (assign the result!)
s := make([]int, n, cap)Slice with length and capacity
len(s) cap(s)Length / capacity
s[1:3] s[:2] s[2:]Sub-slice (shares memory!)
copy(dst, src)Copy elements
slices.Sort(s) slices.Contains(s, x)Sort / contains (slices package)
slices.Reverse(s) slices.Index(s, x) slices.Max(s)Reverse / position / maximum
m := map[string]int{"a": 1}Map literal
m := make(map[string]int)Create an empty map
m["b"] = 2Set
v, ok := m["b"]Read with an existence check
delete(m, "a")Delete an entry
for k, v := range m { }Iterate (random order)
len(m)Number of entries
slices.Sorted(maps.Keys(m))Sorted keys (Go 1.23+)

Strings

strings.ToUpper(s) strings.ToLower(s)Upper/lower case
strings.TrimSpace(s)Remove whitespace at the edges
strings.Split(s, ",") strings.Join(parts, ",")Split / join
strings.Fields(s)Split on any whitespace
strings.Contains(s, "x") strings.HasPrefix(s, "a")Check substring / prefix
strings.Replace(s, "a", "b", -1) strings.ReplaceAll(s, "a", "b")Replace
len(s) len([]rune(s))Length in bytes / in characters
var sb strings.Builder; sb.WriteString("x")Build text efficiently

Structs & interfaces

type P struct { X, Y int }Define a struct
p := P{X: 1, Y: 2} q := &P{1, 2}Create a struct (value / pointer)
func (p *P) Move() { p.X++ }Method with a pointer receiver
type A struct { B }Embedding (composition instead of inheritance)
type I interface { M() string }Interface (satisfied implicitly)
s, ok := v.(string)Type assertion
switch x := v.(type) { case int: }Type switch
Name string `json:"name"`Struct tag for JSON

Errors & panic

if err != nil { return err }Standard error check
errors.New("text")Create a simple error
fmt.Errorf("kontext: %w", err)Wrap an error with context
errors.Is(err, ErrX) errors.As(err, &t)Search the error chain
panic("broken")Abort the program (only for programming errors)
defer func() { recover() }()Catch a panic
log.Fatal(err)Log and end the program with exit code 1

Concurrency

go f()Start a goroutine
ch := make(chan int) make(chan int, 5)Channel (unbuffered / buffered)
ch <- v v := <-ch close(ch)Send, receive, close
for v := range ch { }Receive until closed
select { case v := <-a: case b <- x: default: }Wait on multiple channels
var wg sync.WaitGroup; wg.Add(1); wg.Done(); wg.Wait()Wait for goroutines
mu.Lock(); defer mu.Unlock()Protect a critical section
ctx, cancel := context.WithTimeout(ctx, d)Cancel after a deadline

go tool

go run . go build go installRun / build / install
go mod init name go mod tidyCreate / tidy up a module
go get pfad@versionAdd a dependency
go test ./... go test -race -v ./...Run tests
go fmt ./... go vet ./...Format / static check
go doc fmt.PrintfDocumentation in the terminal