Understanding nil
Start with Understanding nil
nil is the zero value of several reference-capable types, including pointers, slices, maps, functions, channels and interfaces.
What you’ll learn
- Explain the main purpose of understanding nil.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A nil pointer has no target; dereferencing it panics. A nil slice has length and capacity zero and may be appended to. A nil map permits reads and deletion but assigning a key panics. The operation matters more than the word nil itself.
An interface value is nil only when it has neither a dynamic type nor a dynamic value. An interface holding a typed nil pointer is therefore not equal to nil; we revisit this subtlety in the interfaces and errors lessons.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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 ptr *int
var items []int
var ages map[string]int
fmt.Println("Pointer nil:", ptr == nil)
fmt.Println("Slice nil:", items == nil)
items = append(items, 7)
fmt.Println("Appended slice:", items)
fmt.Println("Missing map key:", ages["unknown"])
}
Output
Pointer nil: true
Slice nil: true
Appended slice: [7]
Missing map key: 0Trace what the program does
All three variables initially have nil values. Appending to the nil slice creates usable storage and yields [7]; looking up an absent key in the nil map safely returns int’s zero value, 0.
Avoid common mistakes
- Do not dereference a nil pointer.
- Do not insert into a nil map before initializing it with
makeor a literal.
Try it yourself
Create a nil slice of strings, append two names, and confirm its length. Compare this with a nil map before trying to write into it.
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 Understanding nil 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.