dongyihang3575 2019-08-20 06:00
浏览 44
已采纳

在Go中通过反射创建结构

I want to define a struct completely dynamically, so that I can get the following struct, but without defining it first?

type Data struct {
   a string
   b int `json:"b"`
}
d := Data{}
  • 写回答

1条回答 默认 最新

  • dqx24298 2019-08-20 12:49
    关注

    An application can create a struct programmatically using reflect.StructOf, but all fields in the struct must be exported.

    The question gets the struct as a value, but it's likely that a pointer to the struct is more useful to the application.

    Given the above, this answer shows how to do the following without defining the type at compile time:

    type Data struct {
       A string `json:"a"`
       B int `json:"b"`
    }
    var d interface{} = &Data{}
    

    The code is:

    t := reflect.StructOf([]reflect.StructField{
        {
            Name: "A",
            Type: reflect.TypeOf(int(0)),
            Tag:  `json:"a"`,
        },
        {
            Name: "B",
            Type: reflect.TypeOf(""),
            Tag:  `json:"B"`,
        },
    })
    d := reflect.New(t).Interface()
    

    Here's a runnable example that sets some fields: https://play.golang.org/p/uik7Ph8_BRH

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了