【问题标题】:Can we use Type Assertion with interface method in Go?我们可以在 Go 中将类型断言与接口方法一起使用吗?
【发布时间】:2021-06-03 03:19:20
【问题描述】:

我正在尝试在 Go 中键入 assert,但错误说 struct 没有实现接口方法,但我已经明确实现了接口中声明的方法。

这是我要执行的代码

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

【问题讨论】:

    标签: go


    【解决方案1】:

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

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

    我们有:

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

    然后代码将编译。但由于e 拥有*Like 的实例,而不是Like 之一,因此测试:

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

    现在打印falseSee the complete example here.

    何时以及是否使用指针接收器的问题是一个非常基本的问题,并且在Go Tour 中得到了很好的解决,尽管没有明确说明。 The FAQ has the same information in a more compact form,还有一些explicit details in a second section。另见Value receiver vs. pointer receiver

    【讨论】:

      【解决方案2】:

      指针类型和非指针类型不一样。你需要这样做:

      _, f := e.(*Like)
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 2013-08-14
        • 1970-01-01
        • 2012-04-25
        • 2022-01-04
        • 2012-07-13
        相关资源
        最近更新 更多