Reputation: 2486
I'm trying to get at the Doc
s and Comment
s of struct
s and struct field
s, but I can't seem to be able to do so, they just turn up empty:
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
src := `package test
// Hello
type A struct {
// Where
B int // Are you
}
`
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, 0)
if err != nil {
panic(err)
}
ast.Inspect(f, func(n ast.Node) bool {
switch t := n.(type) {
case *ast.TypeSpec:
fmt.Println(t.Doc.Text())
case *ast.StructType:
for _, field := range t.Fields.List {
fmt.Println(field.Doc.Text())
fmt.Println(field.Comment.Text())
}
}
return true
})
}
yields three blank lines: https://play.golang.org/p/4Eh9gS-PUg
Saw the similar question Go parser not detecting Doc comments on struct type but when trying to run the accepted example it turns up all empty — so I'm wondering if something has changed since that version.
Upvotes: 6
Views: 2978
Reputation: 749
In order to get comments, you have to pass the parser.ParseComments flag in argument to parser.ParseFile():
parser.ParseFile(fset, "", src, parser.ParseComments)
All possible mode flags are documented here:
https://golang.org/pkg/go/parser/#Mode
Upvotes: 14