This code does not run correctly :
package main
import "fmt"
type Human interface {
myStereotype() string
}
type Man struct {
}
func (m Man) myStereotype() string {
return "I'm going fishing."
}
type Woman struct {
}
func (m Woman) myStereotype() string {
return "I'm going shopping."
}
func main() {
var m *Man
m = new (Man)
w := new (Woman)
var hArr []*Human
hArr = append(hArr, m)
hArr = append(hArr, w)
for n, _ := range (hArr) {
fmt.Println("I'm a human, and my stereotype is: ",
hArr[n].myStereotype())
}
}
It exists with :
tmp/sandbox637505301/main.go:29:18: cannot use m (type *Man) as type *Human in append:
*Human is pointer to interface, not interface
tmp/sandbox637505301/main.go:30:18: cannot use w (type *Woman) as type *Human in append:
*Human is pointer to interface, not interface
tmp/sandbox637505301/main.go:36:67: hArr[n].myStereotype undefined (type *Human is pointer to interface, not interface)
But this one runs correctly (var hArr []*Human is rewritten into var hArr []Human) :
package main
import "fmt"
type Human interface {
myStereotype() string
}
type Man struct {
}
func (m Man) myStereotype() string {
return "I'm going fishing."
}
type Woman struct {
}
func (m Woman) myStereotype() string {
return "I'm going shopping."
}
func main() {
var m *Man
m = new (Man)
w := new (Woman)
var hArr []Human // <== !!!!!! CHANGED HERE !!!!!!
hArr = append(hArr, m)
hArr = append(hArr, w)
for n, _ := range (hArr) {
fmt.Println("I'm a human, and my stereotype is: ",
hArr[n].myStereotype())
}
}
Output is ok:
I'm a human, and my stereotype is: I'm going fishing.
I'm a human, and my stereotype is: I'm going shopping.
And I do not understand why. As m and w are pointers, why when I define hArr as an array of pointers on Human the code fails ?
Thank you for your explanation