type T struct {
Tp int
}
func (t T) Set(a int) {
t.Tp = a
}
func main() {
t := T{}
fmt.Println(reflect.TypeOf(t.Set))
fmt.Println(reflect.TypeOf(T.Set))
}
result :
func(int)
func(main.T, int)
why T.set is not equal to t.set?
what is principle or translation bebind this?
t.Set is a method value. T.Set is a method expression.
The method value t.Set
yields a function equivalent to:
func(a int) ( t.Set(a) }
The method expression T.Set
yields a function that is equivalent to the method with the receiver as the first argument.
func(t T, a int) { t.Set(a) }
This playground example illustrates the difference between the method value and method expression.
Separate from this discussion about method expressions and method values, the function Set should take a pointer receiver. Otherwise, the change to t is discarded.
func (t *T) Set(a int) {
t.Tp = a
}
Here's the example with the pointer receiver.