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)
}
提示错误
# 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)
因为我只实现*person
的接口,而没实现person
的接口,所以在sayHeight
时,需要将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)
}

网友评论