Go 接口与指针接收器的问题

2020-02-08  本文已影响0人  ProgrammingGuy
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)
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读