How do you create a new instance of a struct from its type at run time in Go?

后端 未结 5 1573
清歌不尽
清歌不尽 2020-12-02 06:07

In Go, how do you create the instance of an object from its type at run time? I suppose you would also need to get the actual type of the object first too?

5条回答
  •  日久生厌
    2020-12-02 06:14

    You can use reflect.Zero() which will return the representation of the zero value of the struct type. (similar to if you did var foo StructType) This is different from reflect.New() as the latter will dynamically allocate the struct and give you a pointer, similar to new(StructType)

提交回复
热议问题