Go语言如何对未知类型的变量执行内存初始化操作?
Go运行时为未知类型分配内存实现方案
问题根因
Go语言内置的new是编译期关键字,仅支持传入静态确定的类型,无法接收运行时通过反射获取的reflect.Type类型变量,因此无法直接用new实现动态类型的内存分配。
正确实现代码
你需要使用标准库reflect提供的运行时内存分配能力,修正后的AllocateNew函数如下:
package main import "reflect" type MyStruct struct { Name string Surname string } type ExpandedStruct struct { BasicInfo MyStruct Phone int } func AllocateNew(model interface{}) interface{} { // 获取入参的反射类型对象 originType := reflect.TypeOf(model) // 兼容入参为指针的场景,避免返回二级指针 if originType.Kind() == reflect.Ptr { originType = originType.Elem() } // 运行时分配对应类型的零值内存,返回指向该实例的反射值对象 newInstance := reflect.New(originType) // 将反射值转回普通interface{},实际类型为指向目标类型的指针 return newInstance.Interface() } func main() { first := MyStruct{} // 断言为对应指针类型即可正常使用 firstAllocated := AllocateNew(first).(*MyStruct) firstAllocated.Name = "张" firstAllocated.Surname = "三" println(firstAllocated.Name, firstAllocated.Surname) second := ExpandedStruct{} secondAllocated := AllocateNew(second).(*ExpandedStruct) secondAllocated.Phone = 13800138000 println(secondAllocated.Phone) }
代码说明
- 函数支持传入任意结构体值或结构体指针作为参数,返回的结果都是对应结构体类型的指针实例,效果和静态分配的
&MyStruct{}完全一致 - 如果需要返回值类型而非指针,可以在最后调用
newInstance.Elem().Interface()即可
内容的提问来源于stack exchange,提问作者jmilic1
相关产品推荐
相关产品推荐

