Create a gist now

Instantly share code, notes, and snippets.

@nametake /main.go
Last active Apr 30, 2017

What would you like to do?
Goのコードの中から文字列のhoge変数を見つけるコード
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
fset := token.NewFileSet()
expr, err := parser.ParseFile(fset, "./hoge.go", nil, 0)
if err != nil {
panic(err)
}
// ast.Print(fset, expr)
ast.Inspect(expr, func(n ast.Node) bool {
ident, ok := n.(*ast.Ident)
if !ok {
return true
}
if ident.Name != "hoge" {
return true
}
vs, ok := ident.Obj.Decl.(*ast.ValueSpec)
if !ok {
return true
}
bl, ok := vs.Values[0].(*ast.BasicLit)
if !ok {
return true
}
if bl.Kind != token.STRING {
return true
}
fmt.Println(fset.Position(ident.Pos()))
return true
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment