Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. Zero Values

Zero Values

In Go, a "zero value" is automatically assigned to a variable when it is declared, based on its type. This is one of Go's safety features that prevents bugs caused by forgetting to initialize variables.

Syntax list

TypeZero valueDescription
int, int8, int16, int32, int640The zero value for all integer types is 0.
uint, uint8 (byte), uint16, uint32, uint640The zero value for all unsigned integer types is also 0.
float32, float640.0The zero value for floating-point types is 0.0.
complex64, complex1280+0iThe zero value for complex types is 0 for both the real and imaginary parts.
string""The zero value for strings is an empty string.
boolfalseThe zero value for booleans is false.
pointer (*T)nilThe zero value for pointers is nil.
slice ([]T)nilA nil slice has a length of 0, and you can use append on it.
map (map[K]V)nilWriting to a nil map causes a panic.
channel (chan T)nilSending to or receiving from a nil channel blocks forever.
function (func)nilThe zero value for function types is nil.
interfacenilThe zero value for interfaces is nil.
structeach field's zero valueAll fields of a struct are initialized to their respective zero values.
array ([N]T)each element's zero valueAll elements of an array are initialized to the zero value of their type.

Sample code

package main

import "fmt"

type Person struct {
	Name string
	Age  int
	Active bool
}

func main() {
	// Zero values for basic types
	var n int
	var f float64
	var s string
	var b bool
	fmt.Printf("int: %d, float64: %f, string: %q, bool: %v\n", n, f, s, b)

	// Zero values for pointer, slice, and map
	var p *int
	var sl []int
	var m map[string]int
	fmt.Println(p, sl, m)              // <nil> [] map[]
	fmt.Println(p == nil, sl == nil, m == nil) // true true true

	// Appending to a nil slice is safe
	sl = append(sl, 1, 2, 3)
	fmt.Println(sl) // [1 2 3]

	// Zero value for a struct
	var person Person
	fmt.Println(person) // { 0 false}
	// Using zero values for condition checks
	if person.Name == "" {
		fmt.Println("Name is not set")
	}
}

Overview

Thanks to zero values, Go lets you safely use uninitialized variables. For example, a counter variable has a zero value of 0, so you can increment it immediately after declaration without any issues.

A nil slice and an empty slice ([]int{}) both have a len() of 0, but they differ in whether they are nil. Writing to a nil map causes a panic, so always initialize a map before using it.

Designing with zero values in mind is a Go idiom known as the "useful zero value." When structuring a struct so that its zero-value state represents a meaningful initial state, you can keep your code concise.

If you find any errors or copyright issues, please .