Dieser Code nicht korrekt ausgeführt:go Vererbung und Polymorphismus
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())
}
}
Es existiert mit:
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)
Aber dieses läuft richtig (var harr [] * Mensch in var harr [neu geschrieben ] Mensch):
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())
}
}
Ausgang ist 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.
Und ich verstehe nicht warum. Wie m und w sind Zeiger, warum, wenn ich hArr als ein Array von Zeigern auf Mensch definieren, der Code fehlschlägt?
Vielen Dank für Ihre Erklärung
Go hat keine Vererbung, daher gibt es keinen Polymorphismus vom Typ "ist a". – JimB
Mögliches Duplikat von [Verwenden von Schnittstellen zum Erstellen einer Warteschlange für beliebige Typen] (https://stackoverflow.com/questions/35595810/using-interfaces-to-create-a-queue-for-arbitrary-types) – IanAuld