Trace automatic addressing and dereferencing
Trace automatic addressing and dereferencing
Go permits x.M() for a pointer receiver when x is addressable and (&x) has method M. A pointer can also call a value-receiver method through implicit dereferencing. These are conveniences for selectors and calls, not changes to the method set of a value type.
package main
import ( "fmt")
type Count int
func (c *Count) Inc() { *c++ }func (c Count) Value() int { return int(c) }func main() { var c Count = 5 c.Inc() p := &c fmt.Println(p.Value())}c is a local variable, so c.Inc() means (&c).Inc(). p.Value() reads the value through p. The expression *c++ in the method increments the pointed-to value (equivalent to (*c)++). A nil pointer cannot be dereferenced safely.
Expected output:
6Addressability of slice and map elements
package main
import ( "fmt")
type Count int
func (c *Count) Inc() { (*c)++ }func main() { s := []Count{1} s[0].Inc() m := map[string]Count{"a": 1} v := m["a"] v.Inc() m["a"] = v fmt.Println(s[0], m["a"])}A slice element is addressable, but a map element is not. m["a"].Inc() would not compile. Copy the map value to a variable, call the method and assign it back. A function result of value type is likewise not addressable for a pointer-receiver call.
Expected output:
2 2Try it locally
Define Level int with pointer method Raise() adding 2. Start a map entry at 3, update it via a temporary variable, and print 5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 03: Trace automatic addressing and dereferencing
Check the lesson objective before moving on.
Why can a local value variable call a pointer method?
How can you update a map value using a pointer method?