gpt4 book ai didi

pointers - 如何定义接收指针的 Go 接口(interface)方法的实现?

转载 作者:IT王子 更新时间:2023-10-29 01:58:05 26 4
gpt4 key购买 nike

下面的程序运行良好。

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()
}

这是输出。

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

但是,当我更改 Hello 方法以接收指针时,出现错误。

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()
}

这是错误。

$ 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)

如何修复第二个程序?

最佳答案

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

p 是类型*Person*Joker 实现接口(interface)Person,还原invokeHello 到:

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

这将修复第二个程序。

我认为你对 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.

关于pointers - 如何定义接收指针的 Go 接口(interface)方法的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43601858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com