Table of contents
In Go (also referred to as Golang), when you declare a variable without explicitly initializing it with a value, it is given a default value. This default value is called the "zero value" for its type. Here's what the zero values are for some common types in Go:
int:
0
float64:
0.0
bool:
false
string:
""
(empty string)pointer:
nil
slice:
nil
map:
nil
channels:
nil
functions:
nil
interfaces:
nil
array: Array of appropriate length filled with zero values for the array's type. For example, the zero value of [3]int is [0, 0, 0].
Here's a simple example:
package main
import "fmt"
func main() {
var i int
var f float64
var b bool
var s string
fmt.Printf("%v %v %v %q\n", i, f, b, s)
}
When run, this program will print:
0 0 false ""
Exercises:
Basic Zero Values:
Declare a variable of type
*int
and print its value.Declare a variable of type
[]string
and print its value.Declare a variable of type
map[string]int
and print its value.
Struct Zero Values:
Define a struct
Person
withName
as a string andAge
as an int.Declare a variable of type
Person
and print its value.
Zero Value Functionality:
Declare a slice of ints.
Without initializing the slice, try to append a value to it and print the result.
Solutions:
- Basic Zero Values:
package main
import "fmt"
func main() {
var ptr *int
var slice []string
var m map[string]int
fmt.Println(ptr, slice, m)
}
Output:
<nil> [] <nil>
- Struct Zero Values:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
var p Person
fmt.Println(p)
}
Output:
{ 0}
- Zero Value Functionality:
package main
import "fmt"
func main() {
var numbers []int
numbers = append(numbers, 5)
fmt.Println(numbers)
}
Output:
[5]
This demonstrates that even though the zero value of a slice is nil
, you can still use append()
with it.