Read method values and expressions
Read method values and expressions
A method value such as p.Total binds a receiver and produces a function. A method expression such as Product.Total produces a function whose first argument is the receiver. Both can be stored in variables and called later, but their parameter lists differ.
package main
import ( "fmt")
type Product struct{ Price int }
func (p Product) Total(q int) int { return p.Price * q }func main() { p := Product{Price: 4} f := p.Total g := Product.Total p.Price = 6 fmt.Println(f(3), g(p, 3))}The method value saved the value receiver when f was created, before Price changed. The method expression g uses the receiver supplied at call time. Its function type is func(Product, int) int, whereas f is func(int) int.
Expected output:
12 18Capture a pointer receiver
package main
import ( "fmt")
type Counter int
func (c *Counter) Add(n int) { *c += Counter(n) }func main() { var a Counter = 1 var b Counter = 10 p := &a f := p.Add p = &b f(2) (*Counter).Add(p, 5) fmt.Println(a, b)}f saved the pointer to a, not the variable p itself. Reassigning p does not change the stored pointer. The expression (*Counter).Add receives a pointer explicitly. A value-type expression Counter.Add is invalid because Add is not in the value method set.
Expected output:
3 15Try it locally
Define Rate int with value method Charge(units int) int. Bind a method value to rate 3, change rate to 5, and print the old bound charge and new expression charge for 2 units.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 04: Read method values and expressions
Check the lesson objective before moving on.
Which expression binds the current receiver p?
What is the first argument of Product.Total as a function?