In these two tutorial examples, why does a method with a pointer receiver satisfy an interface in one case but not the other?
In example #55 the class Vertex
doesn't satisfy the Abser
interface because method Abs
is only defined for *Vertex
and not Vertex
:
type Abser interface {
Abs() float64
}
type Vertex struct {
X, Y float64
}
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
The error message is:
prog.go:22: cannot use v (type Vertex) as type Abser in assignment:
Vertex does not implement Abser (Abs method has pointer receiver)
But in example #57, the class MyError
satisfies the error
interface ok even though Error()
is defined for *MyError
and not MyError
:
type error interface {
Error() string
}
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("at %v, %s",
e.When, e.What)
}
From the description in this answer, it seems like both should work ok, but the tutorial demonstrates the first one failing. What's the difference?