要获取类型,您需要查看
Type可能是an
ast.StarExpr或an 的属性
ast.Ident。
这里看看这个:
package mainimport ( "fmt" "go/ast" "go/parser" "go/token")func main() { // src is the input for which we want to inspect the AST. src := `package mypack// type hello is a cool typetype hello string// type notype is not that cooltype notype int// printme is like nothing else.func (x *hello)printme(s string)(notype, error){ return 0, nil}` // Create the AST by parsing src. fset := token.NewFileSet() // positions are relative to fset f, err := parser.ParseFile(fset, "src.go", src, 0) if err != nil { panic(err) } // Inspect the AST and find our function var mf ast.FuncDecl ast.Inspect(f, func(n ast.Node) bool { switch x := n.(type) { case *ast.FuncDecl: mf = *x } return true }) if mf.Recv != nil { for _, v := range mf.Recv.List { fmt.Print("recv type : ") switch xv := v.Type.(type) { case *ast.StarExpr: if si, ok := xv.X.(*ast.Ident); ok { fmt.Println(si.Name) } case *ast.Ident: fmt.Println(xv.Name) } } }}


