英文:
How can I find the root implementation of an interface in Go?
问题
我有一个嵌入在结构体OneConcrete
中的接口RootInterface
。然后,这个接口的具体实现再次作为RootInterface
嵌入到另一个结构体TwoConcrete
中。
我如何确定RootInterface
的实际实现是OneConcrete
?以下代码希望展示了我想要实现的目标:
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) // 输出 true
// 我如何获得等价于 ok == true 的结果,
// 也就是找出 OneConcrete 是实际的
// RootInterface 实现?
_, ok = two.(OneConcrete)
fmt.Println(ok) // 输出 false
}
请注意,我希望得到的答案适用于RootInterface
在结构体层次结构中任意深度嵌入的一般情况。
英文:
I have an interface RootInterface
embedded in a struct OneConcrete
. This concrete implementation of the interface is then embedded into another struct TwoConcrete
as RootInterface
again.
How do I determine that the actual implementation of RootInterface
is OneConcrete
? The following code hopefully shows what I am trying to achieve:
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
}
Note that I would like an answer to the general case where RootInterface
could be embedded arbitrarily deeply within a struct hierarchy.
答案1
得分: 3
OneConcrete
没有嵌入接口。它实现了该接口。嵌入一个类型意味着结构体将获得一个与给定类型同名的额外字段,并且该类型的所有方法将成为结构体的方法。因此,要获取OneConcrete
,你应该执行two.(TwoConcrete).RootInterface.(OneConcrete)
。
英文:
OneConcrete
does not embeds interface. It implements that interface. Embedding a type mean that struct will get one additional field with same name as given type and all methods of that type will become methods of struct. So, to get OneConcrete
you should do two.(TwoConcrete).RootInterface.(OneConcrete)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论