5. Pointer Receivers

A receiver type on a method can be a pointer.

Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are more common than value receivers. However, methods with pointer receivers don't require that a pointer is used to call the method β€” the pointer will automatically be derived from the value.

Pointer Receiver

pointer_receiver.go
type car struct {
	color string
}

func (c *car) setColor(color string) {
	c.color = color
}

func main() {
	c := car{
		color: "white",
	}
	c.setColor("blue")
	fmt.Println(c.color)
	// prints "blue"
}

Non-Pointer Receiver

What Are Receivers?

A receiver lets you attach a method to a type:

Pointer Receiver vs Value Receiver

Pointer Receiver (Can Modify)

  • *car = pointer receiver

  • Changes the original struct

  • Most common when you need to modify the struct

Value Receiver (Cannot Modify)

  • car = value receiver

  • Receives a copy of the struct

  • Changes don't affect the original

Complete Examples

Pointer Receiver Example

Value Receiver Example

Go's Automatic Pointer Magic

You can call pointer receiver methods on values:

Go automatically converts c.setColor() to (&c).setColor() for you.

When to Use Each

1

Use Pointer Receiver

  • You need to modify the struct

  • The struct is large (avoid copying)

  • You want changes to persist

2

Use Value Receiver

  • You're just reading data (not modifying)

  • The struct is small

  • You want the method to be side-effect free

Real-World Example

Comparison to Regular Functions

Method with Pointer Receiver

Equivalent Function

Methods are just syntactic sugar β€” cleaner to write and read.

Common Pattern: Builder Methods

Quick Reference

Type
Syntax
Modifies Original?
Use When

Pointer receiver

func (t *Type)

Yes

Need to modify struct

Value receiver

func (t Type)

No

Just reading data

Key Takeaways

  • Pointer receiver (*Type) - modifies original, most common

  • Value receiver (Type) - works on copy, for read-only operations

  • Go auto-converts - can call c.method() even if method expects *c

  • Choose based on intent - modify = pointer, read = value

  • Methods are cleaner - c.setColor() vs setColor(&c)

Rule of thumb: If the method modifies the receiver, use a pointer receiver.