6

I'm trying to get at the Docs and Comments of structs and struct fields, 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.

salient
  • 2,316
  • 6
  • 28
  • 43

1 Answers1

13

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

Marco Sacchi
  • 712
  • 6
  • 21
R3v4n
  • 739
  • 6
  • 11
  • 3
    ah that was where to look! and now I also realized that the "Hello" comment is on `ast.GenDecl` and not `ast.TypeSpec` – salient Sep 27 '17 at 12:20