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 proper reasoning.
This code is running perfectly:
package main
import (
"fmt"
"math"
)
type Vertex struct{
X,Y float64
}
type Abser interface{
Abs() float64
}
func (v Vertex) Abs() float64{ //method with value receiver argument
return math.Sqrt(v.X*v.X+v.Y*v.Y)
}
func main(){
var myVer Vertex = Vertex{3,4}
var inter Abser
inter = &myVer //assigning *Vertex type to inter
fmt.Println(inter.Abs())
}
Meanwhile, the following code shows an error:
package main
import (
"fmt"
"math"
)
type Vertex struct{
X,Y float64
}
type Abser interface{
Abs() float64
}
func (v *Vertex) Abs() float64{ //method with pointer receiver argument
return math.Sqrt(v.X*v.X+v.Y*v.Y)
}
func main(){
var myVer Vertex = Vertex{3,4}
var inter Abser
inter = myVer //assigning Vertex type to inter
fmt.Println(inter.Abs())
}
The error is:
interface.go:18: cannot use myVer (type Vertex) as type Abser in assignment: Vertex does not implement Abser (Abs method has pointer receiver)
Until reaching this section of the tour, I could understand that the creators of Go have let-go of the cumbersome notations like
(*v).method1name()
(&v).method2name()
So that methods with value receivers can be used with both values and pointers, and vice versa.
Why does the language discriminate between the two (value and pointer) when working with interfaces? Wouldn't it be more convenient if the same reference/dereference principles could apply here?
I hope that I am not missing something too apparent. Thanks!