A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Zero Values

Each type in Go has a default value known as the zero value.

Basic Types

If a variable is declared but not initialized it takes on its zero value.

// Numeric types (Zero value: 0).
var n1 int // 0
var n2 float32 // 0
var n3 float64 // 0
var n4 byte // 0 (alias for uint8)
var n5 rune // 0 (alias for int32)
// Booleans.
var b bool // false
// Strings.
var s string // "" (empty string)

Reference Types

The zero value is nil for slices, maps, pointers, functions, channels and interfaces:

// Slices.
var s []int // nil
// Maps.
var m map[string]int // nil
// Pointers.
var p1 *int // nil
var p2 *float64 // nil
// Functions.
var f func() // nil
// Channels.
var c chan int // nil
// Interfaces.
var i1 interface{} // nil
var i2 any // nil (any is an alias for interface{}, added in Go v1.18)
type I interface {
var i3 I // nil

Struct Type

The zero value for a struct type is a struct value with all the fields set to their zero values:

type Person struct {
Name string
Age int
var p Person // Person{Name: "", Age: 0}
p.Name // "" (empty string)
p.Age // 0