Dave Martorana
Dave Martorana

Reputation: 1331

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

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!

Upvotes: 1

Views: 119

Answers (1)

Ask Bjørn Hansen
Ask Bjørn Hansen

Reputation: 6943

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.

Upvotes: 2

Related Questions