0

I have a package in Go that contains a series of structs. I want to use some form of reflection to:

  1. Get each struct in the package
  2. For each struct in the package, generate a list of the properties + tags values
  3. Export that information to some document

Consider the following:

package mypackage
type StructA struct {
   PropA string `desc:"Some metadata about the property"`
   PropB int `desc:"Some more metadata"`
}
type StructB struct {
   PropZ string `desc:"Some metadata about the property"`
   PropX float `desc:"Some more metadata"`
}
type StructC struct {
   PropY string `desc:"Some metadata about the property"`
   PropQ int `desc:"Some more metadata"`
}


func GenerateDocs() {
   structSlice := somehow.GetStructsIn("mypackage") // How do I do this part??
   for i, typedefinition := range structSlice {
       // Reflection to get the property names and tags for each struct
   }

}

We don't want to instantiate each struct manually. If StructD is added to the module tomorrow, the code should pick it up and perform the action without us needing to update any of the logic.

How can I get the type definition for each struct in the package programmatically?

ravibhagw
  • 1,740
  • 17
  • 28
  • 1
    You must instantiate the types to use reflection. If the types are not used, they may not even exist in the compiled binary. If you want to iterate over everything in a package, you must do that statically before compilation. – JimB Jul 08 '22 at 20:56
  • 1
    @ravibhagw , @JimB — Voting to reopen: I believe he's wanting to use [`parser`](https://pkg.go.dev/go/parser) and [`ast`](https://pkg.go.dev/go/ast) to parse the package into an AST and traverse that to generate some documentation (a report listing each struct and its properties and the tag(s) associated with each property.) – Nicholas Carey Jul 08 '22 at 22:56
  • 1
    See https://medium.com/justforfunc/understanding-go-programs-with-go-parser-c4e88a6edb87 and https://medium.com/swlh/cool-stuff-with-gos-ast-package-pt-1-981460cddcd7 for some details on the how of things. – Nicholas Carey Jul 08 '22 at 23:01
  • 1
    @ravibhagw could also accomplish what it sounds like he wants to do with `go doc` and documentation comments. See https://go.dev/blog/godoc and https://go.dev/doc/comment — that lets you generate docs like this, https://pkg.go.dev/github.com/gin-gonic/gin, but the quality is entirely dependent upon the developer writing decent doc comments. – Nicholas Carey Jul 08 '22 at 23:09
  • 1
    @NicholasCarey I'm leaving closed, the question is still a duplicate even if it's about statically parsing Go source. I edited the other canonicals in – blackgreen Jul 09 '22 at 06:13

0 Answers0