Zero value of a variable in Golang refers to the value it contains till it is not explicitly initialized. Zero value may also be referred as default value of a variable.
[the_ad id=”651″]
A zero value is provided by the compiler in order to allocate space in memory for the variable after it is declared.
This zero value is different for a variable of different data types.
Example, for a variable of bool type, the zero value is false; for integers, it is 0 etc. Thus, below code will print 0.
package main
import "fmt"
func main(){
var int num
fmt.Println(num)
}
Zero value only exists till the variable is not provided a value. Also, below code snippets are equivalent.
var num int var num int = 0 var flag bool var flag bool = false var name string var name string = ""
Below table provides a quick reference to the zero value for each data type.
| Data Type | Zero Value |
|---|---|
| int | 0 |
| float32 | 0 |
| float64 | 0 |
| bool | false |
| string | “” |
| pointers | nil |
| functions | nil |
| slices | nil |
| channels | nil |
| maps | nil |
| interfaces | nil |
An uninitialized array will contain all the elements with the zero value of the type of array. Example,
var arr[5] int fmt.Print(arr)
will print [0,0,0,0,0] since the zero value of int(which is the data type of array) is 0.