英文:
Runtime structure using reflection
问题
假设我有一个以某种yaml文件编写的数据模型。
schema: human
type: object
properties:
name:
type: string
surname:
type: string
我想解析它,并生成以下结构:
type Human struct {
Name string `db:"name"`
Surname string `db:"surname"`
}
是否可以使用反射生成运行时的Go结构体?
英文:
Assume I have data model written in some sort of yaml file.
schema: human
type: object
properties:
name:
type: string
surname:
type: string
I would like to parse it, and generate structure:
type Human struct {
Name string `db:"name"`
Surname string `db:"surname"`
}
Is it possible to generate runtime Go struct using reflection?
答案1
得分: 2
是的,你可以使用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。
但正如其他人所说,有时候最好还是生成代码。反射有时候会有些奇怪,并且在使用时需要非常精确。
英文:
Yes, you can with 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)
Prints
{"name":"","surname":""} <nil>
Playground: https://play.golang.org/p/U4N3bbJ5n8.
But as others have said, sometimes it's better to just generate code. Reflection is kinda wonky at times, and requires a lot of precision when using it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论