以下代码能通过编译吗?为什么?
package main
import (
"fmt"
)
type People interface {
Speak(string) string
}
type Student struct{}
func (stu *Student) Speak(think string) (talk string) {
if think == "love" {
talk = "You are a good boy"
} else {
talk = "hi"
}
return
}
func main() {
var peo People = Student{}
think := "love"
fmt.Println(peo.Speak(think))
}
mark
不能,是 *Student 指针实现了方法。
不能,是 *Student 指针实现了方法。
mark
mk
1111111
发生多态的几个要素: 1、有interface接口,并且有接口定义的方法 2、有子类去重写interface的接口 3、有父类指针指向子类对象 本题中,是*student指针实现了方法
报错了
.\main.go:23:19:
应该改成 var peo People = &Student{} 即可编译通过。(People 为 interface 类型,就是指针类型)
mark
func (stu Student) Speak(think string) (talk string) { if think == "love" { talk = "You are a good boy" } else { talk = "hi" } return }
这样也可以编译通过,输出也是:You are a good boy
所以应该改成 var peo People = &Student{} 即可编译通过。(People 为 interface 类型,就是指针类型)
Student{} 已经重写了父类 People{} 中的 Speak(string) string 方法,那么只需要用父类指针指向子类对象即可。应该改成 var peo People = &Student{}