I would like to parse go code, and more especially the content of a function.
So far it's pretty easy to get the function declaration with the parser.ParseFile
function.
package main
import (
"fmt"
"go/parser"
"go/token"
"go/ast"
"log"
)
var code = []byte(`
package main
import (
"fmt"
)
func GetFoo() {
test := foo()
fmt.Println(test)
}
func foo() int {
return 0
}
`)
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", code, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
for _, decl := range f.Decls {
switch t := decl.(type) {
// That's a func decl !
case *ast.FuncDecl:
fmt.Printf("Function name: %v
", t.Name)
// Now I would like to access to the test var and get its type
// Must be int, because foo() returns an int
}
}
}
Now I would like to access to the test
var and get its type, but I am a little bit lost. I have seen the decl.Body.List
to iterate over the statements but I can get that my test
var is an int
Thank you for your precious help !