Go Cheat Sheet

Essential Go (Golang) syntax and patterns. Variables, functions, structs, interfaces, goroutines, channels, error handling, and common standard library usage.

Variables & Types Functions Structs & Interfaces Control Flow Goroutines & Channels Error Handling Slices & Maps Common Patterns

Variables & Types

var x int = 10 Explicit type declaration
x := 10 Short variable declaration (type inferred)
const Pi = 3.14 Constant declaration
var name string Zero value: "" for strings
var count int Zero value: 0 for numbers
var ok bool Zero value: false for booleans
var p *int Zero value: nil for pointers
int, int8, int16, int32, int64 Signed integer types
uint, uint8 (byte), uint16, uint32, uint64 Unsigned integer types
float32, float64 Floating point types
string, bool, rune Other basic types

Functions

func add(a, b int) int { return a + b } Basic function
func swap(a, b int) (int, int) { return b, a } Multiple return values
func divide(a, b float64) (result float64, err error) Named return values
func sum(nums ...int) int Variadic function
fn := func(x int) int { return x * 2 } Anonymous function / closure
defer f.Close() Deferred execution (runs at function exit)
func (r Rect) Area() float64 Method on struct (value receiver)
func (r *Rect) Scale(f float64) Method on struct (pointer receiver)

Structs & Interfaces

type User struct { Name string; Age int } Struct definition
u := User{Name: "Alice", Age: 30} Struct literal
u := User{"Alice", 30} Positional struct literal
type Reader interface { Read(p []byte) (int, error) } Interface definition
type Animal struct { Name string } Base struct for embedding
type Dog struct { Animal; Breed string } Struct embedding (composition)
v, ok := i.(string) Type assertion with check
switch v := i.(type) { case int: ... } Type switch

Control Flow

if x > 0 { ... } If statement
if err := doWork(); err != nil { ... } If with init statement
for i := 0; i < 10; i++ { ... } Classic for loop
for condition { ... } While-style loop
for { ... } Infinite loop
for i, v := range slice { ... } Range over slice
for k, v := range myMap { ... } Range over map
switch day { case "Mon": ... default: ... } Switch statement
select { case msg := <-ch: ... } Select on channels

Goroutines & Channels

go doWork() Launch goroutine
ch := make(chan int) Unbuffered channel
ch := make(chan int, 10) Buffered channel (capacity 10)
ch <- 42 Send value to channel
val := <-ch Receive value from channel
close(ch) Close channel
for v := range ch { ... } Receive until channel closed
var wg sync.WaitGroup WaitGroup for goroutine sync
wg.Add(1); go func() { defer wg.Done(); ... }() Add and signal completion
wg.Wait() Block until all goroutines done

Error Handling

if err != nil { return err } Basic error check
errors.New("something failed") Create simple error
fmt.Errorf("failed at %d: %w", id, err) Wrap error with context
errors.Is(err, os.ErrNotExist) Check error identity
errors.As(err, &pathErr) Extract typed error
panic("fatal error") Panic (unrecoverable)
defer func() { if r := recover(); r != nil { ... } }() Recover from panic

Slices & Maps

s := []int{1, 2, 3} Slice literal
s := make([]int, 0, 10) Make slice (len=0, cap=10)
s = append(s, 4, 5) Append to slice
sub := s[1:3] Slice of slice (index 1 to 2)
len(s), cap(s) Length and capacity
copy(dst, src) Copy slice
m := map[string]int{"a": 1} Map literal
m := make(map[string]int) Make empty map
v, ok := m["key"] Map lookup with existence check
delete(m, "key") Delete map entry

Common Patterns

func init() { ... } Package initializer (runs before main)
type Color int; const (Red Color = iota; Green; Blue) Enum with iota
_ = unusedVar Blank identifier (discard value)
fmt.Sprintf("%s is %d", name, age) String formatting
import "fmt"; import "os" Standard library imports
go mod init mymodule Initialize Go module
go get package@latest Add dependency

More Cheat Sheets