According this question, golang will generate both type-receiver method
and point-receiver method
, which means the code below will work correctly and the value will change unexpectedly.
func (test *Test) modify() {
test.a++
}
func main() {
test := Test{10}
fmt.Println(test)
test.modify()
fmt.Println(test)
}
I think it's acceptable to me. But when this mixes with interface, thing goes wrong.
type Modifiable interface {
modify()
}
type Test struct {
a int
}
func (test *Test) modify() {
test.a++
}
func main() {
test := Test{10}
fmt.Println(test)
test.modify()
fmt.Println(test)
var a Modifiable
a = test
}
it said:
Test does not implement Modifiable (modify method has pointer receiver)
Why will this happen ?
And how golang actually handle method call ?