dthh5038 2017-04-25 04:50
浏览 42

如何定义接收指针的Go接口方法的实现?

The following program runs fine.

package main

import (
    "fmt"
)

type Person interface {
    Hello()
}

type Joker struct {
    Name string
}

func (j Joker) Hello() {
    fmt.Println(j.Name, "says, \"Hello!\"")
}

func main() {
    var j Joker = Joker{"Peter"}
    invokeHello(j)
}

func invokeHello(p Person) {
    p.Hello()
}

Here is the output.

$ go run foo.go
Peter says, "Hello!"

But when I change the Hello method to receive a pointer, I get errors.

package main

import (
    "fmt"
)

type Person interface {
    Hello()
}

type Joker struct {
    Name string
}

func (j *Joker) Hello() {
    fmt.Println(j.Name, "says, \"Hello!\"")
}

func main() {
    var j *Joker = &Joker{"Peter"}
    invokeHello(j)
}

func invokeHello(p *Person) {
    p.Hello()
}

Here are the errors.

$ go run bar.go
# command-line-arguments
./bar.go:21: cannot use j (type *Joker) as type *Person in argument to invokeHello:
    *Person is pointer to interface, not interface
./bar.go:25: p.Hello undefined (type *Person has no field or method Hello)

How can I fix the second program?

  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2017-04-25 05:08
    关注
    func invokeHello(p *Person) {
        p.Hello()
    }
    

    p is type *Person, *Joker implement interface Person, revert invokeHello to:

    func invokeHello(p Person) {
        p.Hello()
    }
    

    this will fix the second program.

    I think you have misleading about golang interface type

    An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分