Skip to content

Instantly share code, notes, and snippets.

@nametake
Last active April 30, 2017 06:49
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 nametake/1fd82014bdfc434a32aba6590c4c66bb to your computer and use it in GitHub Desktop.
Save nametake/1fd82014bdfc434a32aba6590c4c66bb to your computer and use it in GitHub Desktop.
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