【发布时间】:2018-04-18 20:53:18
【问题描述】:
这段代码运行不正确:
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())
}
}
它存在于:
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)
但是这个运行正确(var hArr []*Human 被重写为 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())
}
}
输出没问题:
I'm a human, and my stereotype is: I'm going fishing.
I'm a human, and my stereotype is: I'm going shopping.
我不明白为什么。由于 m 和 w 是指针,为什么当我将 hArr 定义为 Human 上的指针数组时,代码会失败?
谢谢你的解释
【问题讨论】:
-
Go 没有继承,因此不存在“is a”类型多态性。
标签: go polymorphism