如何在Go中获取实现了接口的包中所有定义的类型?

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

How can I get all of the types defined in a package in Go that implement an interface?

问题

如果我有这样的结构:

api > v1 > *.go

我想要能够import api.v1,然后从中反射出满足http.Handler的任何类型。

我已经了解了类型和方法的反射,但是我似乎无法弄清楚如何仅检查具有package v1声明并提取其中定义的所有类型。这个是不可能做到的吗?

谢谢!

英文:

If I have the structure:

api > v1 > *.go

I would like to be able to import api.v1 and from that, reflect out any of the types defined therein that satisfy, say, http.Handler.

I have reflect of types and methods down, but I can't seem to figure out how to just inspect anything that has a package v1 declaration and extract all types defined in there. Is this impossible to do?

Thanks!

答案1

得分: 2

如果您不使用导入的代码,编译器将不会包含它,所以我认为这是不可能的。

如果您以某种方式运行代码(因此它被包含在内),您可以直接调用一个注册函数来注册它自己。

在Go中编程通常不包括您所要求的那种“魔法”。起初,这对我来说感觉有限,但过了一段时间后,我习惯了,并且现在我欣赏事物的本来面目,如果这样说得通的话。

英文:

If you don't use the imported code the compiler will not include it, so I think it's impossible.

If you are running the code somehow anyway (so it is included) you might as well just have it call a register function to register itself.

Programming in Go usually doesn't include the sort of "magic" you are asking for. At first it felt limiting to me, but I got used to it after a while and now I appreciate that things are what they look like, if that makes sense.

huangapple
  • 本文由 发表于 2013年5月2日 06:44:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/16327669.html
匿名

发表评论

匿名网友

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

确定