运行时结构使用反射

huangapple go评论159阅读模式
英文:

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: &quot;Name&quot;, Type: stringType, Tag: reflect.StructTag(`db:&quot;name&quot; json:&quot;name&quot;`)},
	{Name: &quot;Surname&quot;, Type: stringType, Tag: reflect.StructTag(`db:&quot;surname&quot; json:&quot;surname&quot;`)},
})
sv := reflect.New(sType)
svi := sv.Interface()
b, err := json.Marshal(svi)
fmt.Printf(&quot;%s %v&quot;, b, err)

Prints

{&quot;name&quot;:&quot;&quot;,&quot;surname&quot;:&quot;&quot;} &lt;nil&gt;

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.

huangapple
  • 本文由 发表于 2017年4月14日 20:23:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/43411458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定