猿问

Go解析器未检测到结构类型的文档注释

我正在尝试使用 Go 的解析器ast包阅读结构类型的相关文档注释。在此示例中,代码仅使用自身作为源。

package main


import (

    "fmt"

    "go/ast"

    "go/parser"

    "go/token"

)


// FirstType docs

type FirstType struct {

    // FirstMember docs

    FirstMember string

}


// SecondType docs

type SecondType struct {

    // SecondMember docs

    SecondMember string

}


// Main docs

func main() {

    fset := token.NewFileSet() // positions are relative to fset


    d, err := parser.ParseDir(fset, "./", nil, parser.ParseComments)

    if err != nil {

        fmt.Println(err)

        return

    }


    for _, f := range d {

        ast.Inspect(f, func(n ast.Node) bool {

            switch x := n.(type) {

            case *ast.FuncDecl:

                fmt.Printf("%s:\tFuncDecl %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc)

            case *ast.TypeSpec:

                fmt.Printf("%s:\tTypeSpec %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc)

            case *ast.Field:

                fmt.Printf("%s:\tField %s\t%s\n", fset.Position(n.Pos()), x.Names, x.Doc)

            }


            return true

        })

    }

}

func 和字段的注释文档输出没有问题,但由于某种原因,找不到“FirstType 文档”和“SecondType 文档”。我错过了什么?Go 版本是 1.1.2。


料青山看我应如是
浏览 244回答 2
2回答
随时随地看视频慕课网APP

相关分类

Go
我要回答