英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论