gpt4 book ai didi

Go lang func参数类型

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

我正在尝试查找 func 参数类型及其名称以生成一些代码。我正在为它使用 ast 包。我找到了参数名称,但找不到参数类型名称。

for _, fun := range findFunc(node) { //ast.FuncDecl

if fun.Recv != nil {
for _, field := range fun.Type.Params.List {
for _, name := range field.Names {
println(name.Name) //Func field name
//How to find field type name here?
}

}
}

}

最佳答案

你走对了,FuncType.Params 是函数的(传入)参数列表。它的 List 字段包含所有参数,类型为 ast.Field :

type Field struct {
Doc *CommentGroup // associated documentation; or nil
Names []*Ident // field/method/parameter names; or nil if anonymous field
Type Expr // field/method/parameter type
Tag *BasicLit // field tag; or nil
Comment *CommentGroup // line comments; or nil
}

Field.Type 保存接口(interface)类型的参数类型 ast.Expr只需嵌入 ast.Node它只为您提供源代码中类型的开始和结束位置。基本上这应该足以获取类型的文本表示。

让我们看一个简单的例子。我们将分析这个函数:

func myfunc(i int, s string, err error, pt image.Point, x []float64) {}

以及打印其参数(包括类型名称)的代码:

src := `package xx
func myfunc(i int, s string, err error, pt image.Point, x []float64) {}`

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
panic(err)
}
offset := f.Pos()

ast.Inspect(f, func(n ast.Node) bool {
if fd, ok := n.(*ast.FuncDecl); ok {
fmt.Printf("Function: %s, parameters:\n", fd.Name)
for _, param := range fd.Type.Params.List {
fmt.Printf(" Name: %s\n", param.Names[0])
fmt.Printf(" ast type : %T\n", param.Type)
fmt.Printf(" type desc : %+v\n", param.Type)
fmt.Printf(" type name from src: %s\n",
src[param.Type.Pos()-offset:param.Type.End()-offset])
}
}
return true
})

输出(在 Go Playground 上尝试):

Function: myfunc, parameters:
Name: i
ast type : *ast.Ident
type desc : int
type name from src: int
Name: s
ast type : *ast.Ident
type desc : string
type name from src: string
Name: err
ast type : *ast.Ident
type desc : error
type name from src: error
Name: pt
ast type : *ast.SelectorExpr
type desc : &{X:image Sel:Point}
type name from src: image.Point
Name: x
ast type : *ast.ArrayType
type desc : &{Lbrack:71 Len:<nil> Elt:float64}
type name from src: []float64

关于Go lang func参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524607/

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