如何在Golang中获取一个包下的所有结构体?

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

How can i get all struct under a package in Golang?

问题

可以使用反射来列出一个包中所有以结构体形式定义的类型的名称或接口。以下是一个示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func list(packageName string) {
  7. pkg, err := reflect.Import(packageName)
  8. if err != nil {
  9. fmt.Println(err)
  10. return
  11. }
  12. types := pkg.Types()
  13. for _, typeName := range types {
  14. typeObj, err := reflect.ResolveType(typeName)
  15. if err != nil {
  16. fmt.Println(err)
  17. continue
  18. }
  19. if typeObj.Kind() == reflect.Struct {
  20. fmt.Println(typeObj.Name())
  21. }
  22. }
  23. }
  24. func main() {
  25. list("fmt")
  26. }

预期结果:

  1. Formatter
  2. GoStringer
  3. Scanner
  4. State
  5. Stringer

请注意,这只是一个示例代码,实际使用时可能需要根据具体情况进行调整。

英文:

Can we list all struct in the form of name or interface, under a package?
Like:

  1. struct := list("fmt")

expected result:

  1. Formatter
  2. GoStringer
  3. Scanner
  4. State
  5. Stringer

答案1

得分: 3

你能做的最好的方法是解析go源码(可以使用以下命令克隆:hg clone https://code.google.com/p/go/),并且提取出ast.StructType

这就是漂亮打印机所做的事情:

<!-- language-all: go -->

  1. func (P *Printer) Type(t *AST.Type) int {
  2. separator := semicolon;
  3. switch t.form {
  4. case AST.STRUCT, AST.INTERFACE:
  5. switch t.form {
  6. case AST.STRUCT: P.String(t.pos, &quot;struct&quot;);
  7. case AST.INTERFACE: P.String(t.pos, &quot;interface&quot;);
  8. }
  9. if t.list != nil {
  10. P.separator = blank;
  11. P.Fields(t.list, t.end);
  12. }
  13. separator = none;

在同样的思路下,linter go/lintlint.go中也是这样做的:

  1. case *ast.StructType:
  2. for _, f := range v.Fields.List {
  3. for _, id := range f.Names {
  4. check(id, &quot;struct field&quot;)
  5. }
  6. }
  7. }
英文:

The best you can do is parse the go sources (which you can clone: hg clone https://code.google.com/p/go/), and isolate the ast.StructType.

That is what a pretty printer does:

<!-- language-all: go -->

  1. func (P *Printer) Type(t *AST.Type) int {
  2. separator := semicolon;
  3. switch t.form {
  4. case AST.STRUCT, AST.INTERFACE:
  5. switch t.form {
  6. case AST.STRUCT: P.String(t.pos, &quot;struct&quot;);
  7. case AST.INTERFACE: P.String(t.pos, &quot;interface&quot;);
  8. }
  9. if t.list != nil {
  10. P.separator = blank;
  11. P.Fields(t.list, t.end);
  12. }
  13. separator = none;

In the same idea, the linter go/lint does the same in lint.go:

  1. case *ast.StructType:
  2. for _, f := range v.Fields.List {
  3. for _, id := range f.Names {
  4. check(id, &quot;struct field&quot;)
  5. }
  6. }
  7. }

huangapple
  • 本文由 发表于 2014年6月9日 18:10:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/24118011.html
匿名

发表评论

匿名网友

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

确定