【问题标题】:How can I find the root implementation of an interface in Go?如何在 Go 中找到接口的根实现?
【发布时间】:2014-04-30 00:20:53
【问题描述】:

我有一个接口RootInterface 嵌入在结构OneConcrete 中。然后将这个接口的具体实现再次嵌入到另一个结构TwoConcrete 中作为RootInterface

如何确定RootInterface的实际实现是OneConcrete?以下代码有望显示我想要实现的目标:

http://play.golang.org/p/YrwDRwQzDc

package main

import "fmt"

type RootInterface interface {
    GetInt() int
}

type OneConcrete struct {
}

func (oc OneConcrete) GetInt() int {
    return 1
}

type TwoConcrete struct {
    RootInterface
}

func main() {
    one := OneConcrete{}
    fmt.Println("One", one.GetInt())

    two := RootInterface(TwoConcrete{RootInterface: one})

    _, ok := two.(TwoConcrete)
    fmt.Println(ok) // prints true

    // How can I get the equivalent of ok == true,
    // i.e. find out that OneConcrete is the acutal
    // RootInterface implementation?
    _, ok = two.(OneConcrete)
    fmt.Println(ok) // prints false
}

请注意,我想回答RootInterface 可以任意深入地嵌入结构层次结构的一般情况。

【问题讨论】:

    标签: go


    【解决方案1】:

    OneConcrete 不嵌入接口。它实现了那个接口。嵌入类型意味着 struct 将获得一个与给定类型同名的附加字段,并且该类型的所有方法都将成为 struct 的方法。因此,要获得OneConcrete,您应该使用two.(TwoConcrete).RootInterface.(OneConcrete)

    【讨论】:

    • 我明白你的意思。假设我有一个名为FiveConcrete 的结构,我想看看是否有一个TwoConcrete 实现,即五.(FourConcrete).RootInterface.(ThreeConcrete).RootInterface.(TwoConcrete).... Is there a generic way to follow an arbitrary length chain until I find TwoConcrete`还是到达根源?
    • 不可能遍历任意结构嵌入树,因为reflect 包无法区分结构自己的方法和“继承”。而且,如果你的接口有多个方法,如果层次结构中的某些类型重载接口方法之一,则无法定义 root implementation
    猜你喜欢
    • 2018-04-16
    • 2016-05-08
    • 2012-11-29
    • 2021-12-14
    • 2010-10-11
    • 2010-10-29
    • 2016-04-02
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多