What is nil pointer in Go: Explanation and Examples
nil pointer is a pointer variable that does not point to any valid memory address and has the value nil. It means the pointer is empty or uninitialized, and trying to use it without assigning a valid address causes a runtime error called a nil pointer dereference.How It Works
Think of a pointer as a signpost that tells you where to find something in memory. A nil pointer is like a signpost that points to nowhere—it has no address to follow. In Go, when you declare a pointer but don't assign it a value, it automatically points to nil, meaning it doesn't refer to any actual data.
Using a nil pointer is like trying to open a door that doesn't exist; the program will crash with a runtime error. This helps catch bugs early because Go does not allow you to silently use pointers that don't point to valid data.
Example
This example shows a pointer declared without assignment, so it is nil. Trying to access the value it points to causes a runtime panic.
package main import "fmt" func main() { var p *int // p is a pointer to int, currently nil fmt.Println("Pointer p is", p) // prints: Pointer p is <nil> // Uncommenting the next line will cause a runtime panic: // fmt.Println(*p) // dereferencing nil pointer causes panic // To use the pointer safely, assign it an address: x := 10 p = &x fmt.Println("Pointer p now points to value", *p) // prints: Pointer p now points to value 10 }
When to Use
Nil pointers are useful to represent the absence of a value or an uninitialized state in your program. For example, a function can return a nil pointer to indicate "no result" or "not found" instead of returning a zero value.
Always check if a pointer is nil before using it to avoid runtime panics. Nil pointers are common in data structures like linked lists or trees where nodes may or may not exist.
Key Points
- A
nil pointermeans the pointer points to no valid memory. - Dereferencing a nil pointer causes a runtime panic.
- Always check for nil before using pointers.
- Nil pointers can represent missing or optional data.