Zero Values
TL;DR
In Go, there is no such thing as an “uninitialized” variable. If you declare a variable but don’t assign it a value, Go automatically gives it a Zero Value corresponding to its type (e.g., 0 for numbers, "" for strings, nil for pointers/maps/slices).
Mental Model
How It Works
This feature ensures memory safety and predictability. In languages like C, an uninitialized variable contains “garbage” memory leftovers. In Go, it is immediately wiped clean and set to a safe default.
Common Zero Values:
- Numeric types (
int,float64):0 - Booleans (
bool):false - Strings (
string):""(Empty string) - Pointers, functions, interfaces, slices, channels, and maps:
nil
Example
package main
import "fmt"
func main() {
var count int
var isActive bool
var name string
var users []string // A slice
fmt.Printf("count: %v\n", count) // 0
fmt.Printf("isActive: %v\n", isActive) // false
fmt.Printf("name: %q\n", name) // ""
if users == nil {
fmt.Println("users slice is nil") // This prints!
}
}
Common Interview Questions
Can you assign nil to a string in Go?
No. Unlike Java or C#, strings in Go are value types, not references. A string can never be nil. Its zero value is strictly an empty string "". If you need a nullable string (e.g., for JSON parsing where a field might be missing), you must use a string pointer *string.
What is the zero value of a Struct?
The zero value of a struct is the struct itself, with all of its fields recursively set to their respective zero values. For example, var u User results in {Name: "", Age: 0, IsAdmin: false}.