How can I find the root implementation of an interface in Go?

huangapple go评论95阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年4月30日 08:20:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/23377553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定