iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Cheatsheet

A one-screen reference for Go idioms you reach for daily: syntax, slices, maps, structs, interfaces, goroutines + channels, errors, context, testing. Pin it next to your editor.

Go in one page

EXAMPLE
// ===== Vars + declarations =====
var a int = 1            // explicit type
b := 2                   // short var declaration (inside func only)
const Pi = 3.14          // untyped constant

// ===== Built-in types =====
// bool, string, int (int32/int64), uint, byte (uint8), rune (int32),
// float32/float64, complex64/128

// ===== Slices (the dynamic array) =====
xs := []int{1, 2, 3}     // composite literal
ys := make([]int, 0, 32) // len=0, cap=32 — avoids growth allocations
ys = append(ys, 1, 2, 3)
zs := xs[1:3]            // slice [1,3) — backs the same array; copy if needed
copied := make([]int, len(xs)); copy(copied, xs)
for i, v := range xs { _ = i; _ = v }

// ===== Maps =====
m := map[string]int{"a": 1}
m["b"] = 2
v, ok := m["c"]          // ok=false if missing
delete(m, "a")
for k, v := range m { _ = k; _ = v }   // iteration order is RANDOM

// ===== Structs =====
type Order struct {
    ID       string
    Customer string `json:"customer"`
    Total    int    `json:"total_cents"`
}
o := Order{ID: "o1", Customer: "alice", Total: 4995}
op := &o
op.Total = 5000          // automatic deref on field access

// ===== Methods + interfaces =====
type Stringer interface { String() string }

func (o Order) String() string { return o.ID + " " + o.Customer }
var _ Stringer = Order{}     // compile-time interface satisfaction check

// ===== Error handling =====
v, err := strconv.Atoi("42")
if err != nil { return fmt.Errorf("parse: %w", err) }
// wrap with %w; unwrap with errors.Is / errors.As
if errors.Is(err, fs.ErrNotExist) { /* ... */ }
var pErr *fs.PathError
if errors.As(err, &pErr) { _ = pErr.Path }

// ===== Goroutines + channels =====
ch := make(chan int, 16) // buffered
go func() { ch <- 1; close(ch) }()
for v := range ch { _ = v }

select {
case v := <-ch:           _ = v
case ch <- 1:             // send
case <-time.After(1*time.Second):
default:
}

// ===== sync primitives =====
var mu sync.Mutex; mu.Lock(); defer mu.Unlock()
var wg sync.WaitGroup; wg.Add(1); go func(){ defer wg.Done() }(); wg.Wait()
var once sync.Once; once.Do(func(){ /* init */ })

// ===== context =====
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)

// ===== Defer + cleanup =====
f, err := os.Open("x.txt")
if err != nil { return err }
defer f.Close()

// ===== Generics (Go 1.18+) =====
func Map[T, U any](xs []T, f func(T) U) []U {
    out := make([]U, len(xs))
    for i, x := range xs { out[i] = f(x) }
    return out
}

// ===== Testing =====
func TestAdd(t *testing.T) {
    if got, want := 2+3, 5; got != want { t.Errorf("got %d want %d", got, want) }
}
// go test ./...
// go test -race ./...
// go test -bench=. -benchmem

// ===== HTTP server (tiny) =====
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "ok")
})
http.ListenAndServe(":8080", nil)

// ===== JSON =====
b, _ := json.Marshal(o)
var got Order; _ = json.Unmarshal(b, &got)

// ===== Tooling =====
// go run main.go
// go build -o bin/app ./cmd/api
// go fmt ./...; go vet ./...; gofumpt -w .
// staticcheck ./...; golangci-lint run

// ===== Pitfalls =====
// - nil map cannot be assigned to (make first)
// - reading from a closed channel returns zero + ok=false
// - goroutines leak if you forget to cancel the context they listen on
// - range over a slice copies elements; use index when you need pointer-stable
// - defer runs in LIFO order; the args are evaluated AT defer time

Why it matters

Reach for `go vet ./...`, `gofumpt -w .`, and `golangci-lint run` in every CI. They catch most of the "looks fine on a Friday, breaks on Monday" issues — unused imports, shadowed variables, mismatched format strings — at the PR stage rather than in production.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
go run | build | test | fmt | vet | mod | get
Try it Yourself »

Discussion

Loading…