栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何解析方法声明?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何解析方法声明?

要获取类型,您需要查看

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) }        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号