Go Methods Need a Pointer Receiver to Change Their Struct
Go attaches methods to types through a receiver, written before the method name. A value receiver (func (u User) ...) gets a copy of the struct, so any change it makes is lost when the method returns. A pointer receiver (func (u *User) ...) gets the address of the original, so changes stick. Go passes everything by value; pointers are how a function reaches the caller's data.
Structs and Receivers
type User struct {
FirstName string
LastName string
Age int
}
func (u User) FullName() string { // value receiver: reads a copy
return u.FirstName + " " + u.LastName
}
func (u *User) Birthday() { // pointer receiver: modifies the original
u.Age++
}
alice := User{FirstName: "Alice", LastName: "Martin", Age: 30}
alice.Birthday() // Go takes &alice automatically
fmt.Println(alice.Age) // 31
The receiver plays the role of self or this, but it is an ordinary named parameter.
Pointers in Two Operators
name := "John"
p := &name // & takes the address: p is a *string
*p = "Jane" // * dereferences: writes through the pointer
fmt.Println(name) // Jane
func rename(ptr *string, newName string) { *ptr = newName }
rename(&name, "Joe")
Choosing a Receiver
- Pointer receiver when the method modifies the struct, when the struct is large (avoids copying), or when it contains something that must not be copied (a
sync.Mutex). - Value receiver for small, immutable-style types.
- Keep one style per type: mixing makes the method set differ between
Tand*T, which decides which one satisfies an interface.
References
- Programming Languages MOC - hub for language notes.
- Go Has a Single Loop Keyword, for - another Go basic.
- A Tour of Go: Pointer receivers - value vs pointer receivers.
- Go FAQ: Should I define methods on values or pointers? - the guidance in full.
Review cards
Flashcard Why does a value receiver not change the original struct?
Because a value receiver gets a copy of the struct, so any changes made within the method are lost when the method returns.
Flashcard When is a value receiver the right choice in Go?
For small, immutable-style types that the method only reads. Use a pointer receiver when the method modifies the struct, the struct is large, or it holds something that mustn't be copied (a sync.Mutex).