In Go, when memory is allocated to store a value of a type, it is given a default value of that type. Why? Because the zero value makes your code more compact and more straightforward.
Let's look at the zero value of a few types and see how they are useful.
Zero Value
Zero values for all the types are as follows:
- Boolean: false
- Integer : 0
- Floating : 0.0
- String:""
- Interfaces, slices, channels, maps, pointers, and functions: nil
The elements of an array or struct will have their fields zeroed if no value is specified.
type Bar struct {
n int
f float64
next *Bar
}fmt.Println([2]Bar{}) // [{0 0 <nil>} {0 0 <nil>}
Let's see examples to show how these zero values can significantly simplify the API.
Example 1: Slice
The zero value of a slice is nil, so we can use it to check if a slice is empty or not.
var s []int
if s == nil {
fmt.Println("slice is empty")
}
It's interesting to note that:
- A slice value with zero length is not the same as a nil…