ProgrammingGo Backend Developer

How is variable initialization done in Go and what are the dangers of using zero values?

Pass interviews with Hintsage AI assistant

Answer

In Go, variables declared without an explicit initializer automatically receive what are called zero values, which differ for different types:

  • int — 0
  • bool — false
  • string — ""
  • pointers, interfaces, slices, maps, channels, functions — nil

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)

A tricky question

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

Examples of real errors due to ignorance of the subtleties of the topic


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 received null — 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.