← Back to Go Course | Chapter 8: Pointers | Lesson 3 of 6

Pointers to Structs

A pointer to a struct is a shortcut note that lets any function reach the exact same original form, instead of everyone scribbling on their own separate photocopy.

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

markup
package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	p := &Point{X: 1, Y: 2}
	fmt.Println(p)
}

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

markup
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)
}

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

markup
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)
}
Common Mistakes
  1. Passing a large struct by value to many functions, causing unnecessary copying, when a pointer would be more efficient.
  2. Using a value receiver method when the goal is actually to modify the struct's own fields through a method call.
  3. Forgetting struct pointer literals use &Type{...} syntax to create and get the address in one step.
Chapter Summary
  • &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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.