【发布时间】: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