【问题标题】:return interface by embedding type通过嵌入类型返回接口
【发布时间】:2019-10-17 06:16:49
【问题描述】:

我需要返回一个接口。但我得到一个错误:

cannot use B literal (type B) as type K in return argument:
    B does not implement K (missing Check method)

我想当我嵌入类型时,我得到了所有内部类型和接口类型的方法

package main

import (
    "fmt"
)

type K interface {
    Check()
}

type A struct {
    A string
}

type B struct {
    B A
}

func (a A) Check() {
    fmt.Println(a.A)
}

func newB(a A) K {
    return B{B: a}
}

func main() {
    a := A{A: "A struct"}
    b := newB(a)

    b.Check()

}

如何解决这个问题?

【问题讨论】:

    标签: go struct interface


    【解决方案1】:

    这不是嵌入:

    type B struct {
        B A
    }
    

    有了以上内容,你有:

    var b B
    b.B.Check()
    

    这是嵌入:

    type B struct {
      A
    }
    

    有了以上内容,你有:

    var b B
    b.Check()
    

    你还有:

    b.A.Check()
    

    【讨论】:

      【解决方案2】:

      B 没有 Check 方法,并且在您的示例代码中没有任何地方进行任何嵌入。只需让 B 实施检查。错误信息很清楚。

      【讨论】:

      • 再次体验围棋之旅,专注于“嵌入”。
      • 我知道错误说我需要添加方法检查。我将 A 嵌入到 B 中。但我希望通过从 B 类型中的 A 获取方法来返回接口(本例中为 K)。
      • 所以基本上我需要 B 类型中的 A 类型的方法并且是 K 类型的方法,而无需显式重写方法来实现 K 接口。
      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2013-06-11
      • 2011-01-25
      相关资源
      最近更新 更多