Golang provides the mechanism to set default values for declared variables.
How does it work?
When we declare a variable without explicit initialization, Golang will allocate memory for such a variable by setting a zero value for it.
var var1 bool
var var2 int
var var3 float64
var var4 string
var var5 *int
var var6 []int
var var7 map[int]string
Let’s see what values are set for the particular variables listed above:
fmt.Printf("%T -> %#v\n", var1, var1)
fmt.Printf("%T -> %#v\n", var2, var2)
fmt.Printf("%T -> %#v\n", var3, var3)
fmt.Printf("%T -> %#v\n", var4, var4)
fmt.Printf("%T -> %#v\n", var5, var5)
fmt.Printf("%T -> %#v\n", var6, var6)
fmt.Printf("%T -> %#v\n", var7, var7)
Output:
bool -> false
int -> 0
float64 -> 0
string -> ""
*int -> (*int)(nil)
[]int -> []int(nil)
map[int]string -> map[int]string(nil)
As you can see for the primitive types like bool, numeric and string the zero value is false
, 0
or ""
respectively, but for more complex types it’s nil
.
This mechanism works recursively, so elements in an array or fields in a struct will be zeroed too (if no value during the initialization is given).
type Example struct {
name string
num int
p *int
}
var var8 Example
fmt.Printf("%T -> %#v\n", var8, var8)
Output:
main.Example -> main.Example{name:"", num:0, p:(*int)(nil)}
Conclusion:
When we declare a variable the allocated memory gets initialized at least to its zero value state.