Skip to content
Codeloom

Cheat Sheets

Go Cheat Sheet

Go syntax essentials — variables, functions, structs, interfaces, goroutines, channels, error handling, and common patterns in one quick reference.

7 sections 27 snippets

Variables and Types

Declarations
var name string = "Alice"
age := 30           // short declaration
const pi = 3.14
var (
    x int
    y float64
    z bool
)
Basic types
string  bool
int  int8  int16  int32  int64
uint  uint8  uint16  uint32  uint64
float32  float64
byte (alias for uint8)
rune (alias for int32)
Type conversion
i := 42
f := float64(i)
s := strconv.Itoa(i)
n, _ := strconv.Atoi("42")
Zero values
// int: 0,  float: 0.0,  bool: false
// string: "",  pointer: nil
// slice/map/chan/func/interface: nil

Slices and Maps

Slices
nums := []int{1, 2, 3}
nums = append(nums, 4, 5)
len(nums)  // 5
cap(nums)  // varies
sub := nums[1:3]  // [2, 3]
Make a slice
s := make([]int, 5)     // len=5, cap=5
s := make([]int, 0, 10) // len=0, cap=10
Maps
m := map[string]int{"a": 1, "b": 2}
m["c"] = 3
val, ok := m["a"]  // val=1, ok=true
delete(m, "b")
len(m)
Iterate
for i, v := range nums { ... }
for k, v := range m { ... }
for i := range nums { ... }  // index only

Functions

Basic function
func add(a, b int) int {
    return a + b
}
Multiple returns
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
Variadic
func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}
sum(1, 2, 3)
Closures
func counter() func() int {
    n := 0
    return func() int {
        n++
        return n
    }
}
Defer
func readFile(path string) {
    f, err := os.Open(path)
    if err != nil { return }
    defer f.Close()
    // use f...
}

Structs and Methods

Define a struct
type User struct {
    Name  string
    Email string
    Age   int
}
Create instances
u := User{Name: "Alice", Age: 30}
p := &User{Name: "Bob"}
u.Name  // "Alice"
Methods
func (u User) String() string {
    return fmt.Sprintf("%s (%d)", u.Name, u.Age)
}

func (u *User) SetAge(age int) {
    u.Age = age  // pointer receiver mutates
}
Embedding
type Admin struct {
    User          // embedded struct
    Permissions []string
}
a := Admin{User: User{Name: "Alice"}, Permissions: []string{"all"}}
a.Name  // promoted from User

Interfaces

Define an interface
type Reader interface {
    Read(p []byte) (n int, err error)
}

type ReadWriter interface {
    Reader
    Writer
}

Interfaces are satisfied implicitly — no 'implements' keyword

Type assertion
var i interface{} = "hello"
s := i.(string)        // panics if wrong
s, ok := i.(string)    // safe
Type switch
switch v := i.(type) {
case string:
    fmt.Println("string:", v)
case int:
    fmt.Println("int:", v)
default:
    fmt.Println("unknown")
}

Error Handling

Check errors
val, err := doSomething()
if err != nil {
    return fmt.Errorf("doSomething: %w", err)
}
Custom errors
type NotFoundError struct {
    ID string
}

func (e *NotFoundError) Error() string {
    return fmt.Sprintf("not found: %s", e.ID)
}
errors.Is and errors.As
if errors.Is(err, os.ErrNotExist) { ... }

var nfe *NotFoundError
if errors.As(err, &nfe) {
    fmt.Println(nfe.ID)
}

Goroutines and Channels

Start a goroutine
go func() {
    fmt.Println("running concurrently")
}()
Channels
ch := make(chan int)     // unbuffered
ch := make(chan int, 10) // buffered
ch <- 42                // send
val := <-ch             // receive
close(ch)
Select
select {
case msg := <-ch1:
    fmt.Println(msg)
case ch2 <- val:
    fmt.Println("sent")
case <-time.After(5 * time.Second):
    fmt.Println("timeout")
}
WaitGroup
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        process(n)
    }(i)
}
wg.Wait()