Section 08
Slices & Maps
Slices and maps are Go's primary collections. No ArrayList, no HashMap class — they are built-in types with dedicated syntax.
Slice vs Java ArrayList
☕ Java — ArrayList
◎ Go — slice
Why Go does thisSlices are not a class — they are a built-in header: (pointer to array, length, capacity). Append may allocate a new backing array and return a new header. This is why you must always write
msgs = append(msgs, ...) — the original variable may point to the old array.Slice internals — the three-field header
slice header: pointer + length + capacity
Slice sharing — the gotcha
sub-slices share the backing array
Map vs Java HashMap
☕ Java — HashMap
◎ Go — map
Why Go does thisGo maps never return null — they return the zero value of the value type. The two-value form
val, ok := m[key] is how you distinguish "key exists with zero value" from "key does not exist". Always use the two-value form when absence matters.⚙Maps are NOT safe for concurrent access. If two goroutines read/write simultaneously you get a data race. This is fixed with
sync.RWMutex or sync.Map, covered in the Sync Primitives section.