Who can tell (or link where to read), why when a type do implementing an interface there is a difference in behavior (depending on how to transfer the recipient)? Here so it works:
type GetNamer interface {
GetName()
}
type Person struct {
PersonName string
}
func (p Person) GetName() {
fmt.Println(p.PersonName)
}
type Data []GetNamer
var d = Data{
Person{"Vasya"},
}
But, if I pass the recipient by the link: (p *Person) I get an error that types (Person and GetNamer) do not match.
The reason is that when you change the receiver signature to (p *Person)
it means that *Person
implements the interface, not Person
, so your "Data" array must be changed to match.
That is, you must change the signature of the interface method and the contents of the "d" variable to contain Person pointers and it should work, since &Person{...}
is a *Person
which is a GetNamer:
func (p *Person) GetName() {
// ...
}
var d = Data{
&Person{"Vasya"},
}