Code-Memo

Data structures (advanced)

Slice internals

A slice is (ptr, len, cap). append may copy to a larger backing array when len == cap. Sharing subslices shares storage — mutations visible across aliases.

a := []int{1, 2, 3, 4}
b := a[1:3] // shares backing array with a
Map internals

Maps grow dynamically; iteration order is randomized. Do not depend on key order.

Set with map
set := map[string]struct{}{}
set["a"] = struct{}{}
_, exists := set["a"]
delete(set, "a")
container/list and container/heap

Doubly-linked list and heap over sort.Interface / generics-based patterns — useful but not always faster than slices for small n.

Ring buffer

Implement with slice + two indices for fixed-capacity queues.

String ↔ []byte

Conversions allocate a copy unless you use unsafe (expert-only). Prefer bytes package for byte-oriented text.

Copy vs reference

Slices and maps are small headers referencing underlying data; assign copies the header, not deep data.

Slices package (Go 1.21+)

golang.org/x/exp/slices graduated: slices.Sort, slices.BinarySearch, slices.Contains, etc.