In Go, variables declared without an explicit initializer automatically receive what are called zero values, which differ for different types:
int — 0bool — falsestring — ""This is convenient (no garbage in memory), but it can be dangerous: for certain types, such as slices and maps, working with a nil value can lead to panics or bugs.
Example:
var m map[string]int m["key"] = 1 // panic: assignment to entry in nil map var s []int fmt.Println(s, s == nil) // [] true (you can add elements, but you cannot index)
What is the difference between a nil slice and a nil map/channel, and what bugs does this lead to?
The correct answer: A slice with a nil value can be passed to functions, used in append and range — this is safe, but working with a nil map will lead to a panic when trying to write (but reading is allowed and will return a zero value).
Example:
var m map[string]int fmt.Println(m["no_key"]) // 0 — safe m["key"] = 1 // panic! var s []int s = append(s, 42) // okay
Story
Description: In a large project, uninitialized maps were used for data aggregation. During the first write, the application consistently crashed with a panic. The problem was discovered in production when new statistics were introduced.
Story
Description: The service serialized an uninitialized slice, sending it as JSON in the API response. Instead of
[], clients receivednull— it was necessary to change the schema on the frontend to handle both cases.
Story
Description: In the caching module, a nil map was incorrectly compared to an empty map, leading to incorrect determination of whether elements existed. This resulted in unnecessary database calls, reducing performance.