英文:
Get names of structs that implement an interface or inherit a struct
问题
使用反射,可以获取表示实现某个接口或继承自特定结构体的所有类型名称的字符串切片,这些类型位于特定包中。
英文:
Is it possible to get a slice of strings that represent the names of all types that implement an interface or inherit from a specific struct in a specific package using reflection?
答案1
得分: 4
在对reflect
包的文档进行一些研究后,我认为这是不可能的。这不是Go语言中反射的工作方式:接口机制不是声明式的(而是鸭子类型),所以没有这样的类型列表。
话虽如此,你可以尝试使用ast
包来解析你的项目,获取类型列表,并检查它们是否实现了某个接口,然后编写一些代码来生成所需的切片。这会增加编译的步骤,但可能会非常有效。
英文:
After some research on the reflect
package's doc, I don't think it's possible. That's not the way reflection work in go: the interfaces mechanism not beeing declarative (but duck-typed instead), there is no such list of types.
That said, you may have more luck using the ast
package to parse your project, get the list of types, and check wheter or not they implement an interface, then write some code to give you the said slice. That would add a step to compilation, but could work like a charm.
答案2
得分: 2
据我所知,使用reflect
是无法做到这一点的,因为包的范围超出了reflect
的范畴。
你可以像godoc的静态分析工作一样来实现。也就是说,使用code.google.com/p/go.tools/go/types
来解析包的源代码并获取类型信息。
英文:
AFAIK, you can't do this with reflect
, since packages are kinda out of reflect
's scope.
You can do this the same way godoc's static analysis works. That is, using code.google.com/p/go.tools/go/types
to parse the package's source code and get the type info.
答案3
得分: 2
go oracle可以做到这一点。https://godoc.org/code.google.com/p/go.tools/oracle
英文:
The go oracle can do this. https://godoc.org/code.google.com/p/go.tools/oracle
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论