gpt4 book ai didi

go - 获取结构字段类型的简单字符串表示

转载 作者:IT老高 更新时间:2023-10-28 13:08:54 25 4
gpt4 key购买 nike

使用 Go 的 ast package ,我像这样循环遍历结构的字段列表:

type Thing struct {
Field1 string
Field2 []int
Field3 map[byte]float64
}

// typ is a *ast.StructType representing the above
for _, fld := range typ.Fields.List {
// get fld.Type as string
}

...并希望获得 fld.Type 的简单字符串表示形式,就像它出现在源代码中一样,例如[]intmap[byte]float64.

ast 包field type类型属性是一个Expr,所以我发现自己开始使用类型开关并专门处理每种类型——当我唯一的目标是取出每个字段右侧的纯字符串时名字,看起来应该更简单些。

有简单的方法吗?

最佳答案

你可以在这里得到两件事,一个是表达式的type,它最终会在编译期间解决,另一个是code,它将确定该类型。

翻阅文档,我不相信第一个可用。但是,您可以稍后通过在 Node 上使用 End()Pos() .

快速示例程序:

package main

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

func main() {
src := `
package foo

type Thing struct {
Field1 string
Field2 []int
Field3 map[byte]float64
}`

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", src, 0)

if err != nil {
panic(err)
}

// hard coding looking these up
typeDecl := f.Decls[0].(*ast.GenDecl)
structDecl := typeDecl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType)
fields := structDecl.Fields.List

for _, field := range fields {
typeExpr := field.Type

start := typeExpr.Pos() - 1
end := typeExpr.End() - 1

// grab it in source
typeInSource := src[start:end]

fmt.Println(typeInSource)
}

}

打印出来:

string
[]int
map[byte]float64

我通过这个一起在golang playground ,如果你想弄乱它。

关于go - 获取结构字段类型的简单字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20234342/

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