Pointers
- Version
- 1.27
- Review
- Draft
Summary#
&x takes the address of a variable, and *p reads or writes what a pointer refers to. Arguments are passed by value, so pass a pointer when a function must change the caller's variable.
Syntax#
p := &value
*p = replacement
empty := new(int)
limit := new(25)
Example#
package main
import "fmt"
type account struct{ balance int }
func depositCopy(a account, amount int) { a.balance += amount }
func deposit(a *account, amount int) { a.balance += amount }
func main() {
savings := account{balance: 100}
depositCopy(savings, 50)
fmt.Println(savings.balance)
deposit(&savings, 50)
fmt.Println(savings.balance)
field := &savings.balance
*field -= 30
fmt.Println(savings.balance, *field)
count := new(int) // points to zero
*count++
limit := new(25) // points to 25
fmt.Println(*count, *limit)
var missing *account
fmt.Println(missing == nil)
}
Expected output#
100
150
120 120
1 25
true
Common mistakes#
Reading or writing through a nil pointer panics, including field access such as missing.balance. Check for nil where it is a valid input. Copies of a pointer refer to the same variable. To allocate a separate variable initialized with the value of x, use new(x).
Version applicability#
Pointer operations and new(T) date back to Go 1.0. The complete example requires Go 1.26 for new(25). Earlier versions accept only a type in new, so declare a variable and take its address.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0