Cheatsheet: Go

Last updated 2026-08-15

Variables and Types

Declare variables

name := "Alice"
var age int = 30
var height float64 = 1.72
active := true

Zero values and constants

var count int      // 0
var title string   // ""
var ok bool        // false
const pi = 3.14159

Arrays and type conversion

nums := [3]int{1, 2, 3}
value := 42
text := fmt.Sprintf("%d", value)
size := int64(value)

Control Flow

if / else

score := 88
if score >= 90 {
    grade := "A"
    fmt.Println(grade)
} else if score >= 80 {
    fmt.Println("B")
} else {
    fmt.Println("C")
}

for loop forms

for i := 0; i < 3; i++ {
    fmt.Println(i)
}

count := 0
for count < 3 {
    count++
}

switch

day := "sat"
switch day {
case "sat", "sun":
    fmt.Println("weekend")
default:
    fmt.Println("weekday")
}

range over collections

nums := []int{10, 20, 30}
for i, n := range nums {
    fmt.Println(i, n)
}

Slices and Maps

Create and append to slices

nums := []int{1, 2, 3}
nums = append(nums, 4)
firstTwo := nums[:2]

make and copy

buf := make([]byte, 0, 16)
buf = append(buf, 'a', 'b')
clone := make([]byte, len(buf))
copy(clone, buf)

Maps

user := map[string]int{"alice": 1, "bob": 2}
user["carol"] = 3
id, ok := user["alice"]
delete(user, "bob")

Structs and Methods

Define a struct

type User struct {
    Name string
    Age  int
}

u := User{Name: "Alice", Age: 30}

Methods

type Counter struct {
    Value int
}

func (c *Counter) Inc() {
    c.Value++
}

func (c Counter) String() string {
    return fmt.Sprintf("%d", c.Value)
}

Embedded structs

type Address struct {
    City string
}

type Customer struct {
    Name string
    Address
}

c := Customer{Name: "Ana", Address: Address{City: "Porto"}}

Interfaces

Define and use an interface

type Speaker interface {
    Speak() string
}

type Dog struct{}

func (Dog) Speak() string {
    return "woof"
}

func say(s Speaker) {
    fmt.Println(s.Speak())
}

Empty interface replacement

var value any = map[string]int{"count": 3}
fmt.Printf("%T\n", value)

Goroutines and Channels

Start a goroutine

go func() {
    fmt.Println("running in background")
}()

Send and receive on a channel

messages := make(chan string)

go func() {
    messages <- "done"
}()

msg := <-messages

Buffered channel and range

jobs := make(chan int, 2)
jobs <- 1
jobs <- 2
close(jobs)

for job := range jobs {
    fmt.Println(job)
}

Error Handling

Return and check errors

file, err := os.Open("data.txt")
if err != nil {
    return err
}
defer file.Close()

Wrap errors

if err := saveUser(user); err != nil {
    return fmt.Errorf("save user: %w", err)
}

Handle multiple return values

value, err := strconv.Atoi("42")
if err != nil {
    fmt.Println("invalid number")
    return
}
fmt.Println(value)

Common stdlib patterns

String formatting with fmt

name := "Alice"
count := 3
text := fmt.Sprintf("%s has %d tasks", name, count)
fmt.Println(text)

Marshal JSON

type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

body, err := json.Marshal(User{Name: "Alice", Age: 30})

Unmarshal JSON

input := []byte(`{"name":"Alice","age":30}`)
var user User
if err := json.Unmarshal(input, &user); err != nil {
    return err
}