Skip to content

Instantly share code, notes, and snippets.

@osamu329
Created November 29, 2019 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osamu329/1af0d40f257977837eb712c73ff3a253 to your computer and use it in GitHub Desktop.
Save osamu329/1af0d40f257977837eb712c73ff3a253 to your computer and use it in GitHub Desktop.
go/ast Doc の確認
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
// Sample.
//go:hoge
type Sample struct {
Field int // First.
}
// type (
type (
// sample
Sample2 struct {
Field2 int
}
)
func main() {
var fs token.FileSet
f, err := parser.ParseFile(&fs, "main.go", nil, parser.ParseComments)
if err != nil {
fmt.Printf("%s\n", err)
}
ast.Inspect(f, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.GenDecl:
if n.Doc != nil {
for _, c := range n.Doc.List {
fmt.Printf("%s %T %q\n", fs.PositionFor(n.Pos(), false), n, c.Text)
}
}
case *ast.TypeSpec:
if n.Doc != nil {
for _, c := range n.Doc.List {
fmt.Printf("%s %T %q\n", fs.PositionFor(n.Pos(), false), n, c.Text)
}
}
case *ast.File:
}
return true
})
}
main.go:12:1 *ast.GenDecl "// Sample."
main.go:12:1 *ast.GenDecl "//go:hoge"
main.go:17:1 *ast.GenDecl "// type ("
main.go:19:2 *ast.TypeSpec "// sample"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment