gpt4 book ai didi

go - 解析 go src,尝试将 *ast.GenDecl 转换为 types.Interface

转载 作者:IT王子 更新时间:2023-10-29 01:02:30 25 4
gpt4 key购买 nike

我正在尝试解析包含接口(interface)的源文件并找到接口(interface)定义的方法/签名。我正在使用 ast 来解析文件。我能够获得一些高级声明,例如 *ast.GenDecl,但我无法进入下一个级别来确定此类型是否为接口(interface)及其方法是什么。

这是我试图解决的脚手架类型问题,用户定义服务的接口(interface),工具将构建服务的骨架

package main

import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"reflect"
)

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 _, v := range f.Decls {

switch t := v.(type) {
case *ast.FuncDecl:
fmt.Println("func ", t.Name.Name)
case *ast.GenDecl:
switch x := t.Specs[0].(type) {
default:
fmt.Println(x, reflect.TypeOf(x))
}
default:
fmt.Printf("skipping %t\n", t)
}

}
}

结果是,但我似乎根本找不到关于接口(interface)声明内部的任何信息。

&{<nil> ServiceInterface 0x8202d8260 <nil>} *ast.TypeSpec

最佳答案

在使用 AST 时,我发现使用 spew 转储示例很有帮助包裹:

    fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, "/tmp/tmp.go", `package service ....`)
spew.Dump(f)

我发现从 spew 输出中编写所需的代码很容易。

这里有一些代码可以帮助您入门。它打印接口(interface)和方法名称:

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

关于go - 解析 go src,尝试将 *ast.GenDecl 转换为 types.Interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com