Method Sets Value Versus Pointer Receivers

The method set of a value type only carries value receivers, so interfaces holding the pointer can call mutators that the plain value cannot reach.

GoData Integrity

Code

gosnippet
40 lines
package main

import "fmt"

type counter struct{ n int }

// value receiver:方法拿到副本,不改原值
func (c counter) value() int { return c.n }

// pointer receiver:方法修改原值
func (c *counter) inc() { c.n++ }

func main() {
	c := counter{}
	// 可寻址变量调用指针方法:编译器自动等价 (&c).inc()
	c.inc()
	fmt.Println("after inc:", c.value())

	// method set of *counter 同时含 value 与 inc:接口装指针两者都能调
	var both interface {
		value() int
		inc()
	} = &c
	both.inc()
	fmt.Println("via interface:", both.value())

	// counter(值类型)的 method set 只含 value:
	// var onlyValue interface{ inc() } = c ← 无法通过编译

	// value receiver 拿到的是副本:拷贝上的自增不回到原值
	copyOf := c
	copyOf.inc()
	fmt.Println("copy:", copyOf.value(), "original:", c.value())

	// 函数传值同理:副本自增,原值不变
	bump(c)
	fmt.Println("after bump:", c.value())
}

func bump(c counter) { c.inc() }

Value versus pointer receivers

Method Sets Value Versus Pointer Receivers reduces to the functions value, inc, main and bump.

Applying it

Entry signature: func (c counter) value() int

The demo output is labeled (after inc:, via interface:, copy:), so each printed line points back to the operation that produced it.

Launch the file; main takes over and steps through inc, value and bump.

Statements that matter

func (c counter) value() int { return c.n }
func (c *counter) inc() { c.n++ }
func bump(c counter) { c.inc() }

Interactive Tools for This Topic

FAQ

What does Method Sets Value Versus Pointer Receivers print when run?
Running the file directly is enough — expect labeled output lines such as `after inc:`, `via interface:`, `copy:`.