Understand Go zero values
Variables start with a defined value
When a variable is declared with a type but without an initializer, Go initializes it to the zero value of that type. For numeric types this is zero, for bool it is false, and for string it is the empty string "". A boolean holds one of two logical values, true or false. A zero value is not an uninitialized or random value.
package main
import "fmt"
func main() { var count int var ready bool var name string fmt.Println(count, ready) fmt.Println("[" + name + "]")}The first line prints 0 false. The second prints []: the two bracket strings surround the empty name. Here + joins strings. Other types, such as pointers and slices, have nil zero values; we will study them in later chapters.
Use or replace the default
package main
import "fmt"
func main() { var count int fmt.Println(count) count = count + 1 fmt.Println(count)}The program prints 0 and 1. A counter can use its default value and then be incremented. Writing var count int = 0 gives the same initial value. Do not confuse an empty string with a string containing a space; the latter contains a character. A declaration var count without a type or initializer is invalid.
Try it locally
Declare an int named visits and a bool named active without initializers. Print both, then set visits to 3 and active to true and print again. Expected lines: 0 false and 3 true.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tokens and Declarations 06: Understand Go zero values
Check the lesson objective before moving on.
What is the initial value of var ready bool?
Which describes the zero value of string?