GoGo · Lesson 8 of 8

Go Cheatsheet

Syntax, slices, maps, errors, and goroutines on one page.

Go
// ── Basics ──────────────────────────────
package main
import "fmt"

func main() {
    x := 42                    // declare + infer
    var y float64 = 3.14       // explicit
    const Pi = 3.14159
    s := fmt.Sprintf("%s is %d", "Ada", x)
    fmt.Println(s)
}

// ── Control flow ────────────────────────
if x > 10 { } else if x > 5 { } else { }
if err := do(); err != nil { }     // init statement

for i := 0; i < 5; i++ { }         // the only loop keyword
for i, v := range items { }
for cond { }                       // "while"
for { }                            // forever

switch day {
case "sat", "sun": rest()
default: work()
}                                  // no fallthrough

// ── Functions ───────────────────────────
func div(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("divide by zero")
    }
    return a / b, nil
}
result, err := div(10, 2)
if err != nil {
    return fmt.Errorf("calc failed: %w", err)  // wrap
}
Go
// ── Slices & maps ───────────────────────
nums := []int{3, 1, 4}
nums = append(nums, 1)
nums[0]; nums[1:3]; len(nums)
grid := make([][]int, rows)

ages := map[string]int{"Ada": 17}
ages["Bob"] = 15
v, ok := ages["Eve"]          // ok=false if missing
delete(ages, "Bob")

// ── Structs & methods ───────────────────
type Dog struct {
    Name string
    Age  int
}
func (d Dog) Bark() string { return d.Name + " woofs" }
func (d *Dog) Birthday()   { d.Age++ }    // pointer = mutates

// ── Interfaces (implicit!) ──────────────
type Speaker interface{ Bark() string }
// Dog satisfies Speaker automatically — no "implements"

// ── Goroutines & channels ───────────────
ch := make(chan string)
go func() { ch <- "done" }()      // concurrent
msg := <-ch                        // blocks until sent

var wg sync.WaitGroup
for _, url := range urls {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fetch(url)
    }()
}
wg.Wait()

// ── Tooling ─────────────────────────────
// go run . | go build | go test ./... | go fmt ./...
// go mod init example.com/app | go get pkg@latest