You're slightly confused about what is implementing what. In this case, *Vertex
is implementing Abser
and not Vertex
to make it so Vertex
does as well, you have to change the receiving type on your implementation of Abs
so that it's not a pointer;
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
} // Vertex implementing Abser here
So the way you're phrasing the question is a bit misleading. The interface requires no change and should receive none. Just fyi, you can have both *Vertex
and Vertex
implement the interface by using the method I put above as well as the one you already have.
This is a point that often trips people up in Go. When you declare func (t SomeType)
you're specifying the receiving type, if this is a pointer like (t *SomeType)
then the thing implementing the interface is not SomeType
but rather *SomeType
. This differs a little from other languages where the method is implemented by the class and it doesn't matter if you're working with a reference or a value. In Go, the class doesn't implement the method, you specify the 'receiving type' - the thing that the method can be called on - that first argument actually gets pushed on the stack and used the same as an argument passed into a method, the distinction is only relevant for compilation (interface fulfillment really is the only reason to have the feature afaik). So, to summarize, if you want Vertex
to implement the Abser
interface which features a single method Abs() float64
then you need to define the function as func (v Vertex) Abs() float64 { ... }
.
Just for the sake of having clear readable code I recommend not having the interface defined for both pointers and values... You can work around that using the address of or dereference operator.