go - 使用反射的运行时结构

标签 go

假设我有用某种 yaml 文件编写的数据模型。

schema: human
type: object
properties:
    name:
        type: string
    surname:
        type: string

我想解析它,并生成结构:

type Human struct {
    Name string `db:"name"`
    Surname string `db:"surname"`
}

是否可以使用反射生成运行时 Go 结构体?

最佳答案

是的,您可以使用 reflect.StructOf :

sType := reflect.StructOf([]reflect.StructField{
    {Name: "Name", Type: stringType, Tag: reflect.StructTag(`db:"name" json:"name"`)},
    {Name: "Surname", Type: stringType, Tag: reflect.StructTag(`db:"surname" json:"surname"`)},
})
sv := reflect.New(sType)
svi := sv.Interface()
b, err := json.Marshal(svi)
fmt.Printf("%s %v", b, err)

打印

{"name":"","surname":""} <nil>

Playground :https://play.golang.org/p/U4N3bbJ5n8 .

但正如其他人所说,有时最好只生成代码。反射有时有点不稳定,使用时需要很高的精度。

关于go - 使用反射的运行时结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411458/

相关文章:

go - 如何改进这个文件读取代码

go - 在 Go 中使用泛型类型结构实现接口(interface)方法

go - 就绪时将值发送到 channel 并读取输出

Golang,带有指针和接口(interface)的用例

php - 无法通过PHP shell_exec在Apache下运行go二进制文件

amazon-web-services - 如何使用 golang 检查 s3 对象大小

java - NodeJS 和 Go 语言的单线程比 Java 的多线程好在哪里?

go - 转换负数

logging - 将结果堆栈跟踪默认写入文件

在 CGO 中使用 C 结构的 golang 结构