首页 > 解决方案 > 查找 *ast.FuncDecl 附加到的结构

问题描述

下面是Handler接口的简单实现:

type someApi struct {
    mu       *sync.RWMutex
}
func (api *someApi) ServeHTTP(w http.ResponseWriter, r *http.Request) {}

func NewSomeApi(mu *sync.RWMutex) *someApi {
    return &someApi{
        mu: mu,
    }
}

func (srv *someApi) Create() {
  // some realisation
}

func Create() {
  // some realisation
}

我想要解析文件go/ast并为函数创建装饰器someApi.Create。用 获取 func 名称很简单*ast.FuncDecl.Name,但是我怎样才能找到Create附加的 funcsomeApi呢?

标签: goabstract-syntax-tree

解决方案


通过迭代来解决这个问题*ast.FuncDecl.Recv.List

for _, l := range fn.Recv.List { // fn is *ast.FuncDecl
    star, ok := l.Type.(*ast.StarExpr)
    if !ok {
        continue
    }
    fmt.Println(star.X) // someApi
} 

推荐阅读