Selectors, indexing, and slicing
Selectors and index or slice expressions look simple, but addressability, map rules, and bounds semantics matter.
Canonical guidance
- selectors may refer to fields or methods, including promoted ones
- indexing a map is different from indexing an array, slice, or string
- full slice expressions can control capacity as well as length
Use when
- diagnosing selector ambiguity or visibility issues
- explaining map lookup behavior
- reviewing subslice and bounds logic
Avoid
- assuming map elements are addressable
- slicing without reasoning about capacity and aliasing
- forgetting that string indexing yields bytes
Preferred pattern
head := s[:n:n]
Anti-pattern
- modifying a shared subslice without noticing it still aliases the original backing array
Explanation: This is tempting because slice syntax is lightweight, but the aliasing and capacity semantics still matter.
Why
- selectors and indexing sit in the middle of many everyday compile-time and runtime mistakes