Pointers and pointer receivers
In Go everything is passed by value: when calling a function each argument is copied. This is safe, because the function cannot damage your variables, but it has two drawbacks. First, you cannot write a function that modifies the original variable. Second, copying large structs on every call is costly. The solution is pointers. A pointer is a variable that holds the memory address of another. They are not as scary as in C: Go does not allow pointer arithmetic and has a garbage collector.
The & and * operators
The pointer type to T is written *T. The & operator in front of a variable produces its address, and the * operator in front of a pointer accesses the value it points to; that is called dereferencing. If p is a pointer to int, *p = 10 changes the original variable. The zero value of a pointer is nil, and dereferencing a nil pointer causes a panic, the most common error with pointers. That is why, when a function may receive a null pointer, you check p != nil before using it. With new(T) a zero value of T is allocated and a pointer to it is obtained.
package main
import "fmt"
func incrementCopy(n int) {
n++ // only the copy changes
}
func incrementPtr(n *int) {
*n++ // changes the original
}
func main() {
x := 5
incrementCopy(x)
fmt.Println(x) // 5
incrementPtr(&x)
fmt.Println(x) // 6
p := &x
*p = 100
fmt.Println(x, *p) // 100 100
var np *int
fmt.Println(np == nil) // true
// fmt.Println(*np) // would panic: nil pointer dereference
q := new(int)
*q = 7
fmt.Println(*q) // 7
}Value and pointer receivers
A method with a value receiver, func (a Account) Balance(), works on a copy: if it modifies a field, the change is lost when it ends. A method with a pointer receiver, func (a *Account) Deposit(n float64), works on the original and can modify it. Go makes life easier: if you have an addressable variable and call acc.Deposit(10), the compiler writes (&acc).Deposit(10) for you. Choose a pointer receiver when the method must modify the value, when the struct is large or when one of its methods already uses a pointer; for consistency, do not mix both styles in the same type.
package main
import (
"errors"
"fmt"
)
type Account struct {
Owner string
balance float64
}
func (a *Account) Deposit(amount float64) {
a.balance += amount
}
func (a *Account) Withdraw(amount float64) error {
if amount > a.balance {
return errors.New("insufficient funds")
}
a.balance -= amount
return nil
}
func (a *Account) Balance() float64 {
return a.balance
}
func NewAccount(owner string) *Account {
return &Account{Owner: owner} // pointer to a new struct
}
func main() {
acc := NewAccount("Ana")
acc.Deposit(100)
if err := acc.Withdraw(250); err != nil {
fmt.Println("error:", err)
}
fmt.Println(acc.Balance()) // 100
}When to use pointers
Do not use pointers by default with small types like int, bool or string: copying them is cheap and the code stays simpler. Use them when you need to mutate, when the value is large, or when you want to represent absence with nil. Also remember that slices, maps and channels already contain an internal reference: you normally do not need a pointer to a map or a slice just to modify its contents. One last detail: it is perfectly safe to return a pointer to a local variable, as NewAccount does; Go decides by itself that this variable must outlive the function.
- &x gives the address of x; *p accesses the pointed value.
- An uninitialized pointer is nil; dereferencing it causes a panic.
- Pointer receiver: can modify the original.
- Value receiver: works on a copy.
- Do not mix value and pointer receivers in the same type.
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères