Zero Values
Start with Go Zero Values
When you declare a variable without an explicit initial value, Go initializes it to the zero value of its type. This rule makes newly declared variables predictable.
What you’ll learn
- Predict zero values of basic types.
- Read formatted empty-string output.
- Understand automatic initialization.
Understand the idea
The zero value of a numeric type is 0, for bool it is false, and for string it is the empty string "". Some reference-like types have the zero value nil, discussed later.
Zero values are real values, not missing or undefined memory. Their meanings still depend on the application: zero units in stock might mean “none,” but zero may not be a meaningful customer ID.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
var count int
var ready bool
var note string
fmt.Printf("count=%d ready=%t note=%q\n", count, ready, note)
}
Output
count=0 ready=false note=""Trace what the program does
No assignment appears before the print call. Go initializes count to 0, ready to false and note to an empty string. The %q verb shows quotation marks around the empty string in output.
Avoid common mistakes
- Zero values do not mean variables are uninitialized garbage.
- An empty string and
nilare different concepts; a string’s zero value is"".
Try it yourself
Declare an uninitialized float64 and print it. Then assign 2.5 and compare the outputs.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Zero Values in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.