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.
Code
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
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.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.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 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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.