Pointers in Go
Understand addresses, dereferencing, nil pointers, pointers with structs and methods, and when to pass pointers to functions.
Pointer Basics
A pointer holds the address of a value. Use `&` to take the address, and `*` to follow a pointer to the value.
1. Getting Address and Dereferencing
Use & to get address; *p to access the value.
Nil Pointers and new
The zero value of a pointer is `nil`. Use `new(T)` to allocate a `T` and get `*T`, or take the address of an existing variable.
1. Zero Value is nil
Uninitialized pointer variables are nil.
Pointers and Functions
Function parameters are passed by value. To let a function modify a variable, pass a pointer and change the value via `*p`.
1. Modifying a Value via Pointer
Compare passing by value vs passing a pointer.
Pointers to Structs
Pointers to structs are common: they avoid copying large structs and let functions modify fields directly.
1. Updating Struct Fields via Pointer
Pass *Struct to modify fields inside a function.
Methods and Automatic Dereferencing
When you have a `*T`, Go lets you write `p.Field` and `p.Method()` instead of `(*p).Field` and `(*p).Method()`. The compiler inserts one level of dereference or address-of where possible.
1. Automatic Dereference for Fields
Access struct fields directly on *T without writing (*p).Field.
2. Methods on Value and Pointer Receivers
Call methods with value or pointer receivers on both T and *T when the value is addressable.
Best Practices with Pointers
Use pointers when you need to modify a value in a function or avoid copying large structs. Check for nil before dereferencing.
1. Guidelines
Simple rules for everyday Go code.