Pointers to Structs
In this page:
Creating a Pointer to a Struct
Prefixing a struct literal with & both creates the struct value and gives you a pointer to it in a single expression, which is extremely common when a function is meant to return an object that will be mutated later.
Example: Creating a Pointer to a Struct
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
p := &Point{X: 1, Y: 2}
fmt.Println(p)
}
Login to try C/C++/Java/PHP code in the editor
Passing Struct Pointers to Functions
Passing a pointer to a struct, rather than the struct itself, lets the called function modify the caller's original data and avoids copying potentially large structs on every call.
Example: Passing Struct Pointers to Functions
package main
import "fmt"
type Account struct {
Balance float64
}
func deposit(a *Account, amount float64) {
a.Balance += amount
}
func main() {
acc := Account{Balance: 100}
deposit(&acc, 50)
fmt.Println(acc.Balance)
}
Login to try C/C++/Java/PHP code in the editor
Field Access via Pointer
Accessing and setting fields through a struct pointer uses the exact same dot notation as a plain struct value, since Go automatically dereferences the pointer for field access.
Example: Field Access via Pointer
package main
import "fmt"
type Book struct {
Title string
Copies int
}
func main() {
b := &Book{Title: "Go Basics", Copies: 3}
b.Copies--
fmt.Println(b.Title, "copies left:", b.Copies)
}
Login to try C/C++/Java/PHP code in the editor
- Passing a large struct by value to many functions, causing unnecessary copying, when a pointer would be more efficient.
- Using a value receiver method when the goal is actually to modify the struct's own fields through a method call.
- Forgetting struct pointer literals use &Type{...} syntax to create and get the address in one step.
- &Type{...} creates a struct and immediately returns a pointer to it.
- Passing a struct pointer to a function lets that function modify the original struct's fields.
- Field access on a struct pointer uses the same dot syntax as a plain struct value.
- Pointer receivers on methods are the standard way to let methods mutate a struct's own state.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: