在Go语言中,我们可以使用类型断言(Type Assertion)来处理接口方法吗?

huangapple go评论95阅读模式
英文:

Can we use Type Assertion with interface method in Go?

问题

我正在尝试在Go语言中使用类型断言,但是错误显示结构体没有实现接口方法,但我已经清楚地实现了接口中声明的方法。

这是我尝试执行的代码:

package interfaces

import "fmt"

type Event interface {
    Accept()
}

type Like struct {
}

// Like实现了Event接口中的Accept方法
func (l *Like) Accept() {
    fmt.Println("like accept")
}

func TypeAssertionExample() {
    var l *Like = &Like{}
    var e Event = l
    _, f := e.(Like) // 即使Like实现了Accept方法,仍然会出现错误
    fmt.Println(f)
}

请注意,我只翻译了代码部分,不包括其他内容。

英文:

I am trying to type assert in Go but error says struct doesn't implement interface method but I have clearly implemented method declared in interface.

This is the code I am trying to execute

package interfaces

import "fmt"

type Event interface {
    Accept()
}

type Like struct {
}

// Like implement Accept method from Event interface
func (l *Like) Accept() {
  fmt.Println("like accept")
}

func TypeAssertionExample() {
 var l *Like = &Like{}
 var e Event = l
 _, f := e.(Like) // error even after Like implemented Accept method 
 fmt.Println(f)
}

答案1

得分: 2

请注意,除了Hymns for Disco建议的内容之外,我们还可以修改你的示例(我已将其更改为在Go Playground上使用的package mainfunc main)以便替换为:

func (l Like) Accept() {
    // code
}

这样代码就可以编译了。但由于e保存的是*Like的实例,而不是Like的实例,所以测试:

_, f := e.(Like)
fmt.Println(f)

现在输出false在这里查看完整的示例

何时以及是否使用指针接收器的问题是相当基础的问题,在Go Tour中有相当好的介绍,尽管没有明确提到。FAQ以更紧凑的形式提供了相同的信息,第二部分提供了一些明确的细节。还可以参考https://stackoverflow.com/q/27775376/1256452。

英文:

Note that in addition to what Hymns for Disco suggested, we can modify your example (I've changed it to package main and func main for use on the Go Playground) so that instead of:

func (l *Like) Accept) {
    // code
}

we have:

func (l Like) Accept() {
    // code
}

and the code will then compile. But since e holds an instance of *Like, not one of Like, the test:

_, f := e.(Like)
fmt.Println(f)

prints false now. See the complete example here.

The question of when and whether to use pointer receivers is quite a basic one, and covered fairly well, though not explicitly, in the Go Tour. The FAQ has the same information in a more compact form, with some explicit details in a second section. See also https://stackoverflow.com/q/27775376/1256452.

答案2

得分: 1

指针类型和非指针类型是不同的。你需要这样做:

_, f := e.(*Like)

注意 *,它与你的变量声明 var l *Like 匹配。

英文:

Pointer types and non-pointer types aren't the same. You need to do this:

_, f := e.(*Like)

Notice the *, matching your variable declaration var l *Like.

huangapple
  • 本文由 发表于 2021年6月3日 11:19:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/67814946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定