1 回答
TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用 AST 時(shí),我發(fā)現(xiàn)使用spew包轉(zhuǎn)儲(chǔ)示例很有幫助:
fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service ....`)
spew.Dump(f)
我發(fā)現(xiàn)從 spew 輸出中編寫(xiě)所需的代碼很容易。
這里有一些代碼可以幫助您入門(mén)。它打印接口和方法名稱:
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service
type ServiceInterface interface {
Create(NewServiceRequest) (JsonResponse, error)
Delete(DelServiceRequest) (JsonResponse, error)
}`, 0)
for _, x := range f.Decls {
if x, ok := x.(*ast.GenDecl); ok {
if x.Tok != token.TYPE {
continue
}
for _, x := range x.Specs {
if x, ok := x.(*ast.TypeSpec); ok {
iname := x.Name
if x, ok := x.Type.(*ast.InterfaceType); ok {
for _, x := range x.Methods.List {
if len(x.Names) == 0 {
continue
}
mname := x.Names[0].Name
fmt.Println("interface:", iname, "method:", mname)
}
}
}
}
}
}
}
http://play.golang.org/p/eNyB7O6FIc
- 1 回答
- 0 關(guān)注
- 178 瀏覽
添加回答
舉報(bào)
