package main
import "fmt"
type mouth interface {
talk()
}
type person struct {
height int
}
func (p *person) talk() {
fmt.Println("我的身高:", p.height)
}
func sayHeight(i mouth) {
i.talk()
}
func main() {
p := person{height: 148}
sayHeight(p)
}
提示錯(cuò)誤
# command-line-arguments
.\main.go:23:11: cannot use p (type person) as type mouth in argument to sayHeight:
person does not implement mouth (talk method has pointer receiver)
因?yàn)槲抑粚?shí)現(xiàn)*person
的接口,而沒實(shí)現(xiàn)person
的接口祖娘,所以在sayHeight
時(shí)阱佛,需要將p
改為&p
。
package main
import "fmt"
type mouth interface {
talk()
}
type person struct {
height int
}
func (p *person) talk() {
fmt.Println("我的身高:", p.height)
}
func sayHeight(i mouth) {
i.talk()
}
func main() {
p := person{height: 148}
sayHeight(&p)
}
image.png