首頁  >  文章  >  後端開發  >  為什麼 Go 解析器和 Ast 套件不檢測結構類型的文件註解?

為什麼 Go 解析器和 Ast 套件不檢測結構類型的文件註解?

DDD
DDD原創
2024-11-14 17:20:02394瀏覽

Why Aren't Go Parser and Ast Packages Detecting Doc Comments on Struct Types?

Go Parser Not Detecting Doc Comments on Struct Type

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.

Understanding the Issue

The go/doc package's readType function suggests that when a TypeSpec does not have associated documentation, the documentation is retrieved from the GenDecl.

Inspecting the AST

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.

An Interesting Observation

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.

Conclusion

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn