Dereferencing Pointers
In this page:
Reading Through a Pointer
Placing * before a pointer variable reads the value it points to. This is how code that only has a pointer can still get at the underlying data.
Example: Reading Through a Pointer
package main
import "fmt"
func main() {
age := 30
p := &age
fmt.Println("age via pointer:", *p)
}
Login to try C/C++/Java/PHP code in the editor
Writing Through a Pointer
Assigning to *p, rather than just reading it, changes the original value the pointer refers to -- this is how a function can modify a caller's variable through a pointer parameter.
Example: Writing Through a Pointer
package main
import "fmt"
func main() {
age := 30
p := &age
*p = 31
fmt.Println("age is now:", age)
}
Login to try C/C++/Java/PHP code in the editor
Nil Pointer Dereferencing Panics
A pointer that hasn't been assigned an address (its zero value) is nil, and attempting to dereference it crashes the program with a runtime panic -- there is no value at address zero to read or write.
Note: Always check 'if p != nil' before dereferencing a pointer that might not have been set.
Example: Nil Pointer Dereferencing Panics
package main
import "fmt"
func safeRead(p *int) {
if p == nil {
fmt.Println("pointer is nil, nothing to read")
return
}
fmt.Println("value:", *p)
}
func main() {
var p *int
safeRead(p)
x := 5
safeRead(&x)
}
Login to try C/C++/Java/PHP code in the editor
Automatic Dereferencing for Struct Fields
When accessing a struct field through a pointer, Go automatically dereferences it for you -- p.Field is shorthand for (*p).Field, so you rarely need to write the explicit dereference for field access.
Example: Automatic Dereferencing for Struct Fields
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
p := &Point{X: 1, Y: 2}
fmt.Println(p.X, p.Y) // shorthand for (*p).X, (*p).Y
}
Login to try C/C++/Java/PHP code in the editor
- Dereferencing a nil pointer, which causes an immediate runtime panic ('invalid memory address or nil pointer dereference').
- Forgetting the * is needed both to declare a pointer type (var p *int) and to dereference a pointer value (*p) -- context determines which.
- Trying to dereference a value that isn't actually a pointer, which the compiler rejects at compile time.
- Dereferencing with *p reads or writes the value a pointer points to.
- Assigning through a dereferenced pointer, *p = value, changes the original variable.
- Dereferencing a nil pointer panics at runtime -- always ensure a pointer is non-nil before dereferencing.
- Struct field access through a pointer, p.Field, is automatically dereferenced -- no need to write (*p).Field.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: