Despite using Go's parser and ast packages, the provided code is unable to detect the documentation comments on the struct types FirstType and SecondType.
The go/doc package's readType function suggests that when a TypeSpec does not have associated documentation, the documentation is retrieved from the GenDecl.
To inspect the AST and address this issue, the following changes were made to the code:
func main() { // ... for _, f := range d { ast.Inspect(f, func(n ast.Node) bool { switch x := n.(type) { // ... case *ast.GenDecl: fmt.Printf("%s:\tGenDecl %s\n", fset.Position(n.Pos()), x.Doc.Text()) } return true }) } }
By including a case for *ast.GenDecl, the program now outputs the lost documentation for FirstType and SecondType.
However, this approach has a limitation when multiple struct types are defined in a single TypeSpec:
// This documents FirstType and SecondType together type ( // FirstType docs FirstType struct { // FirstMember docs FirstMember string } // SecondType docs SecondType struct { // SecondMember docs SecondMember string } )
In this case, the docs become associated with both the GenDecl and the individual TypeSpecs.
While using the AST to parse comments is possible, it's preferable to use the go/doc package to handle this task. The go/doc package can effectively retrieve documentation comments for various Go components, including struct types.
The above is the detailed content of Why Aren't Go Parser and Ast Packages Detecting Doc Comments on Struct Types?. For more information, please follow other related articles on the PHP Chinese website!