Pointer Versus Value Receivers

Show why a value receiver cannot mutate the caller copy and why methods needing mutation must use a pointer receiver, with a compile-level type set view.

GoData Integrity

Code

gosnippet
34 lines
package main

import "fmt"

type Counter struct {
	n int
}

// 值接收者:拿到副本,任何修改都随方法结束丢弃
func (c Counter) bumpValue() Counter {
	c.n++
	return c
}

// 指针接收者:就地修改调用方的变量
func (c *Counter) bump() {
	c.n++
}

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

func main() {
	c := Counter{}
	c.bump() // (&c).bump 的语法糖,可寻址时自动取址
	fmt.Println("after pointer receiver:", c.read())

	d := c.bumpValue() // 副本自增后返回
	fmt.Printf("value receiver kept: %d, caller still %d\n", d.read(), c.read())

	// map 元素不可寻址,必须经指针持有者修改
	registry := map[string]*Counter{"a": {}}
	registry["a"].bump()
	fmt.Println("map-held counter:", registry["a"].read())
}

Order of operations

Pointer Versus Value Receivers keeps everything in the functions bumpValue, bump, read and main.

Applying it

The operative signature here: func (c Counter) bumpValue() Counter

Look for the after pointer receiver:, value receiver kept:, map-held counter: prefixes when the file runs; they tie each line to its step.

There are 3 calls inside main — bump, read and bumpValue — executed top to bottom.

Statements that matter

func (c Counter) read() int { return c.n }
func (c Counter) bumpValue() Counter {
c.n++
return c
}
func (c *Counter) bump() {
c.n++
}

Interactive Tools for This Topic

FAQ

What does Pointer Versus Value Receivers print when run?
The script runs standalone; its 3 labeled outputs include `after pointer receiver:`, `value receiver kept:`, `map-held counter:`.