Code-Memo

Basic data structures and collections

Arrays

Fixed length; size is part of the type [3]int and [4]int are different types.

var a [3]int
a[0] = 10
Slices

A slice is a descriptor (pointer, length, capacity) over an underlying array. Built-in append may allocate a new backing array when capacity is exceeded.

s := []int{1, 2, 3}
s = append(s, 4)
sub := s[1:3] // half-open interval [1,3)

nil slice: length 0; append works. Reading elements does not.

Maps

Unordered key–value structure. Keys must be comparable. A nil map cannot be written to; use make or a composite literal.

m := map[string]int{"a": 1}
m["b"] = 2
v, ok := m["c"] // ok is false if missing
delete(m, "a")
Structs

Group fields under one name. Can embed types for composition.

type Point struct {
	X, Y int
}

p := Point{X: 1, Y: 2}
Pointers

Use pointers to avoid copying large structs or to mutate caller state intentionally.

func inc(p *int) { *p++ }
Strings as read-only byte sequences

Indexing a string yields a byte (not a rune). Range over a string for Unicode code points.

When to use what