实现说明
除了函数 Inc、main,文件里再无其他定义。
使用要点
- 跑完文件,输出里会留下标记——
method value:、counter:、method expression:。
常见问题
运行「方法值对比方法表达式」会打印什么?
运行文件本身,method value:、counter:、method expression: 这些前缀各对应一段演示逻辑。
主签名形如 func (m *Meter) Inc() int
核心语句
func (m *Meter) Inc() int {
m.count++
return m.count
}
代码示例
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)
}