Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Pointer vs Value Receivers | Structs as Behavioral Units
Struct-Based Design in Go

bookPointer vs Value Receivers

Swipe to show menu

Understanding how methods interact with structs is essential in Go, especially when deciding between pointer and value receivers. A value receiver means the method operates on a copy of the struct, so changes made inside the method do not affect the original struct. In contrast, a pointer receiver allows the method to access and modify the original struct's fields, since it receives a reference to the struct's memory location.

Guidelines for choosing receiver types are straightforward:

  • Use a pointer receiver if the method needs to modify the struct's fields;
  • Use a pointer receiver if the struct is large, to avoid copying data unnecessarily;
  • Use a value receiver when the method does not modify the struct and the struct is small and inexpensive to copy.
counter.go

counter.go

copy
1234567891011121314151617181920212223242526272829
package main import ( "fmt" ) type Counter struct { Value int } // Increment uses a value receiver: it operates on a copy of the struct. func (c Counter) Increment() { c.Value++ } // Reset uses a pointer receiver: it can modify the original struct. func (c *Counter) Reset() { c.Value = 0 } func main() { counter := Counter{Value: 10} counter.Increment() fmt.Println("After Increment (value receiver):", counter.Value) // Output: 10 counter.Reset() fmt.Println("After Reset (pointer receiver):", counter.Value) // Output: 0 }

In the Counter example, the difference between receiver types becomes clear. The Increment method uses a value receiver, so it works on a copy of the Counter struct. When you call counter.Increment(), the Value field of the original struct does not change, because the increment happens on a copy that is discarded after the method returns. On the other hand, the Reset method uses a pointer receiver. This allows the method to directly modify the Value field of the original struct, so after calling counter.Reset(), the Value is set to zero.

Choosing between pointer and value receivers affects not only whether a method can modify struct state, but also performance, especially for large structs. Pointer receivers avoid unnecessary copying and allow methods to modify the struct's fields, while value receivers are suitable for methods that do not alter the struct and for small, easily copied structs. Understanding these distinctions helps you design more predictable and efficient Go code.

question mark

When should you use a pointer receiver for a method in Go

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 1. Chapterย 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Sectionย 1. Chapterย 3
some-alt