Last active
April 30, 2017 06:49
-
-
Save nametake/1fd82014bdfc434a32aba6590c4c66bb to your computer and use it in GitHub Desktop.
Goのコードの中から文字列のhoge変数を見つけるコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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