I am 2-days old in the world of Golang, and going through the go tour. I couldn\'t help but notice a peculiarity which I cannot seem to be able to come at terms with a
"Intro++ to Go Interfaces" illustrates the issue:
*Vertex
is a type. It’s the “pointer to aVertex
” type. It’s a distinct type from (non-pointer)Vertex
. The part about it being a pointer is part of its type.
You need consistency of type.
"Methods, Interfaces and Embedded Types in Go":
The rules for determining interface compliance are based on the receiver for those methods and how the interface call is being made.
Here are the rules in the spec for how the compiler determines if the value or pointer for our type implements the interface:
*T
is the set of all methods with receiver *T
or T
This rule is stating that if the interface variable we are using to call a particular interface method contains a pointer, then methods with receivers based on both values and pointers will satisfy the interface.
T
consists of all methods with receiver type T
.This rule is stating that if the interface variable we are using to call a particular interface method contains a value, then only methods with receivers based on values will satisfy the interface.
Karrot Kake's answer about method set is detailed also in go wiki:
The method set of an interface type is its interface.
The concrete value stored in an interface is not addressable, in the same way that a
map
element is not addressable.
Therefore, when you call a method on an interface, it must either have an identical receiver type or it must be directly discernible from the concrete type.Pointer- and value-receiver methods can be called with pointers and values respectively, as you would expect.
Value-receiver methods can be called with pointer values because they can be dereferenced first.
Pointer-receiver methods cannot be called with values, however, because the value stored inside an interface has no address.
("has no address" means actually that it is not addressable)