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.
以上是為什麼 Go 解析器和 Ast 套件不檢測結構類型的文件註解?的詳細內容。更多資訊請關注PHP中文網其他相關文章!