Level: IntermediateGo Lang

Go Methods: Value vs Pointer Receivers Explained

8 min read
Go Methods featured image: value, pointer and method set cards

Go methods are functions that belong to a type, and they are how you add behaviour to your structs. In this post, you will learn how to write them and how value and pointer receivers differ. Then we will run one program that shows the difference clearly.

This lesson builds on Go structs for beginners and Go pointers. We also use ideas from Go functions and Go interfaces. So it helps to read those first.

What Are Go Methods?

A method is a function with one extra part, and that part is the receiver. Before the function name, you write a receiver in parentheses. The receiver says which type the method belongs to. After that, you call the method with a dot, such as c.Value(). After that, you call the method with a dot, such as c.Value().

Think of a remote control. The buttons only make sense for the TV they belong to, because each remote is built for one device. In the same way, a method only makes sense for its type, which is why Go methods feel natural. For example, a Counter can increase, and a Celsius value can convert itself to Fahrenheit.

Go has no classes. Instead, you define a type, usually a struct, and attach methods to it. This keeps the language small, and it still gives you clean, object style code. That is the whole idea behind Go methods.

Why Go Methods Matter

You could write plain functions that take the type as an argument. However, Go methods add real benefits. Here is what they give you.

  • Grouping: behaviour sits next to the data it works on.
  • Shorter calls: c.Inc() reads better than Inc(&c).
  • Interfaces: only types with the right methods can satisfy an interface.
  • Clear intent: the receiver tells readers what the method may change.

Also, you can attach methods to any type you define in your package, not only structs. For instance, type Celsius float64 can have its own methods. That is a handy way to add meaning to a simple number, since the type name explains the unit.

How Go Methods Work

Underneath, a method call is just a function call in disguise. When you write c.Inc(), Go passes c as the first argument. So the big question is what kind of argument it is, and this question decides how Go methods behave. The receiver can be a value or a pointer. That choice changes everything, because it decides what the method can touch.

Go Methods diagram showing a value receiver working on a copy and a pointer receiver changing the original
A value receiver gets a copy of the struct, so changes disappear when the method returns. A pointer receiver gets the address of the original, so changes stay.

Value Receivers

With a value receiver, Go copies the struct before the method runs. The method can read and even change its copy, but the original stays the same. Use this for small types, and also for methods that only read.

Pointer Receivers

With a pointer receiver, Go passes the address of the original. As a result, the method changes the real data. Use this when the method must update the struct. Also use it when the struct is large, because copying would be wasteful.

Calling Pointer Methods on a Value

You may have a plain variable and call a pointer method on it. Luckily, Go helps you here. If c is addressable, then c.Inc() is a short form of (&c).Inc(). As a result, you rarely type the ampersand yourself.

Go Methods: Value vs Pointer Receivers

The two kinds of receiver differ in several ways. The table below compares them side by side.

FeatureValue receiverPointer receiver
Receiver syntaxfunc (c Counter)func (c *Counter)
GetsA copy of the valueThe address of the original
Can change the original?NoYes
Cost for large structsCopies all fieldsCopies one address
Works on nil?Panics on a nil pointerCan check for nil
Method set of the valueIncludes itExcludes it
Go Methods diagram showing the method sets of Counter and the Counter pointer type
Interface rules: the type Counter has only value methods in its method set, while the pointer type has both value and pointer methods.

The last row matters for interfaces. In short, the method set of Counter holds only value receiver methods. Meanwhile, *Counter holds both kinds. Therefore, if an interface needs a pointer method, you must pass a pointer. Our Go interfaces post covers this idea in more detail.

Go Methods Hands-On: A Counter

Now let’s write the code. Here we build a Counter with one method of each kind, so you can compare them.

Step 1: Define the Type and Methods

First, Counter holds one number, which is easy to watch. Next, IncByValue uses a value receiver, so it changes a copy. Then Inc uses a pointer receiver, so it changes the original. Finally, Value only reads, so a value receiver is fine.

type Counter struct{ n int }

func (c Counter) IncByValue() { c.n++ }

func (c *Counter) Inc() { c.n++ }

func (c Counter) Value() int { return c.n }

type Valuer interface{ Value() int }
type Incer interface{ Inc() }

type Celsius float64

func (c Celsius) ToF() float64 { return float64(c)*9/5 + 32 }

Let’s look at the key lines. Both interfaces ask for one method each, so they are easy to read. The type Celsius shows that Go methods can belong to a plain number type.

Step 2: Call the Methods

Then we call each method and print the result. We also store the counter in two interfaces, so we can see how the method sets work.

func main() {
	c := Counter{}
	c.IncByValue()
	fmt.Println("after IncByValue:", c.Value())
	c.Inc()
	c.Inc()
	fmt.Println("after Inc twice:", c.Value())

	var v Valuer = c
	var i Incer = &c
	i.Inc()
	fmt.Println("via interfaces:", v.Value(), c.Value())

	temp := Celsius(100)
	fmt.Printf("%.1f C = %.1f F\n", float64(temp), temp.ToF())

	var np *Counter
	fmt.Println("nil pointer is nil:", np == nil)
}

Here is the real output from our run.

after IncByValue: 0
after Inc twice: 2
via interfaces: 2 3
100.0 C = 212.0 F
nil pointer is nil: true

As you can see, IncByValue did nothing to the original, because it worked on a copy. Then the two Inc calls raised the value to 2. The interface line also shows something subtle. The Valuer holds a copy made when c was 2, so it still reads 2. After i.Inc(), the real counter is 3, so the two numbers differ. This output proves the difference between the two receivers.

Step 3: See the Compile Error

What if you try to store the plain value in the Incer interface? Then Go refuses to compile it. The message also explains the problem well.

cannot use Counter{} (value of struct type Counter) as Incer value in variable declaration: Counter does not implement Incer (method Inc has pointer receiver)

This error is a gift, because it tells you exactly what to fix. You should pass &Counter{} instead.

Which Receiver Should You Pick?

A simple rule helps in most cases. Ask three questions. Does the method change the struct? Is the struct large? Does the type already use pointer receivers elsewhere? When the answer to any is yes, choose a pointer receiver. Otherwise, a value receiver is fine. The table below turns the rule into examples.

TypeExampleReceiverReason
Small read-only valueCelsius, a numberValueCopy is cheap and safe
Struct that changesCounter, AccountPointerUpdates must stay
Large structA config with many fieldsPointerAvoids a big copy
Struct with a mutexA cachePointerA copy would break the lock
Small struct, read onlyA point with x and yValueSimple and predictable

When you are unsure, start with a pointer receiver. It is the safer default for structs, because it avoids surprise copies. Later, you can switch a small read-only type to a value receiver if it makes the code clearer.

Do not mix both kinds on one type unless you have a strong reason. Mixed receivers confuse readers, and they can break interface rules. So pick one style per type and keep to it.

Common Mistakes with Go Methods

  • Changing a copy by accident: a value receiver cannot update the original. So use a pointer receiver when you need changes to stick.
  • Mixing receiver kinds: this makes the method set hard to predict. Therefore, choose one kind per type.
  • Calling a method on a nil pointer: a value receiver panics. Instead, use a pointer receiver and check for nil inside.
  • Copying a struct that holds a mutex: the copy has its own lock state. So use a pointer receiver for such types.
  • Storing a value where a pointer is needed: the compiler stops you, as we saw. Pass the address instead.

Best Practices for Go Methods

  • Use pointer receivers for types that change, because the changes then reach the caller.
  • Use value receivers for small, read-only types, since copies are cheap and safe.
  • Keep receiver names short, such as c for a counter, because they appear in every method.
  • Never name the receiver this or self, since Go style prefers a short type-based name.
  • Add methods to named types, such as Celsius, when they give a number a clear meaning.
  • Keep Go methods small, so each one is easy to test.

Practice Task

To practise Go methods, add a Reset method to Counter that sets the value back to zero. Then add a String method that prints Counter(3) for a counter with value 3.

Hint: Reset needs a pointer receiver, because it changes the struct. After that, print the counter with fmt.Println(c) and see how String changes the output.

Official Resources

These pages describe the language rules used in this lesson.

Quick Recap

  • Go methods are functions with a receiver that belongs to a type.
  • A value receiver works on a copy, and a pointer receiver works on the original.
  • Go lets you call a pointer method on an addressable variable.
  • The method set of a value type excludes pointer methods.
  • Pick one receiver kind per type, and prefer pointers for types that change.
  • Any named type, even a number type, can have methods.

What’s Next?

By now, you can attach behaviour to your own types. However, many of the most useful interfaces in Go come from the standard library. So next, we will study io.Reader and io.Writer, which are two of the smallest and most powerful ones.

Next up: Go Reader and Writer interfaces explained