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

DDD
Release: 2024-11-14 17:20:02
Original
400 people have browsed it

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
        })
    }
}
Copy after login

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
    }
)
Copy after login

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.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template