假设我有用某种 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/