RSS DEV Community

Go Basics: Why nil Slices accept new values, but nil Maps don't

Applying new values to a nil slice in Go works as expected, but adding new values to a nil map throws a runtime error. A nil slice can be appended to because it checks its capacity and allocates a new underlying array if necessary. A slice consists of three components: a pointer to the underlying array, the length of the slice, and the capacity of the slice. When a nil slice is declared, its length and capacity are zero, and it doesn't point to an underlying array. The append operation then allocates a new array and returns a new slice. On the other hand, a nil map in Go is uninitialized and not ready to store key-value pairs. This is because a map acts as a hash table and its internal data structures need to be initialized first. To avoid runtime errors, a map should be initialized using the make function before adding values. Initializing a map with make allows it to store key-value pairs without errors. In contrast to nil slices, nil maps require explicit initialization before use. This difference in behavior is due to the underlying data structures and how they are implemented in Go. Understanding the differences between slices and maps is essential for writing effective and error-free Go code.
dev.to
dev.to