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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.