In Go language, there is a certain difference between the receiver of the general method and the receiver of the interface method.
- In general
If the defined receiver is a value, it can be called using a value or a pointer;
If the defined receiver is a pointer, it can be called using a value or a pointer.
- In the interface method
If the defined receiver is a value, it can be called with either an interface value or an interface pointer;
If the defined receiver is a pointer, it can only be called with an interface pointer, not with an interface value.
As shown in the following example:
package main import "fmt" type T struct { S string } type I interface { A() B() } func (t T) A() { () } func (t *T) B() { () } func main() { t := T{"normal method"} pt := &t () () () () //var i I = T{"interface method"} var i I = &T{"interface method"} () () }
If usedvar i I = &T{"interface method"}
Then it can be executed.
If usedvar i I = T{"interface method"}
An error is reported:
./:30:6: cannot use T{...} (type T) as type I in assignment:
T does not implement I (B method has pointer receiver)
It prompts that method B uses the pointer receiver and cannot be called by the interface value.
So, why is there such a difference? For more information about the differences between different recipients of Go methods, please follow my other related articles!