Method Value Versus Method Expression

A method value binds its receiver into a reusable func, while a method expression passes the receiver explicitly as the first argument of the same method.

GoData Integrity

Code

gosnippet
29 lines
package main

import "fmt"

type Meter struct {
	count int
}

func (m *Meter) Inc() int {
	m.count++
	return m.count
}

func main() {
	m := &Meter{}

	// method value: m.Inc binds the receiver now, so calls carry no receiver
	bound := m.Inc
	fmt.Println("method value:", bound(), bound(), bound())
	fmt.Println("counter:", m.count)

	// method expression: Meter.Inc takes the receiver as its first argument
	expr := (*Meter).Inc
	fmt.Println("method expression:", expr(m), expr(m))
	fmt.Println("counter:", m.count)

	// versus: both forms dispatch to the same underlying method
	fmt.Println("counter advanced by both:", m.count)
}

Inside the snippet

Structurally, expect the functions Inc and main and nothing else.

Caveats

  • Standard-library end to end — copy it in and it runs.

Putting it to use

Entry signature: func (m *Meter) Inc() int

The demo output is labeled (method value:, counter:, method expression:), so every line in the printed output names the step that produced it.

Core lines under the microscope

func (m *Meter) Inc() int {
	m.count++
	return m.count
}

Interactive Tools for This Topic

FAQ

What does Method Value Versus Method Expression print when run?
Execute the whole file; each printed line is prefixed with a label like `method value:`, `counter:`, `method expression:`.