使用reflect.Zero()
而不是reflect.New()
.reflect.New()
分配给定类型的值,并返回指向它的指针(包装在reflect.Value
中).
reflect.Zero()
不分配新值,它返回给定类型的零值(包装在reflect.Value
中).因此,如果您传递*int
的reflect.Type
描述符或任何其他指针类型,因为指针类型的零值是nil
,所以您将返回nil
指针.
例如:
var i int
varType := reflect.TypeOf(i)
v := reflect.Zero(reflect.PtrTo(varType)).Interface()
fmt.Printf("Type: %T, Value: %v\n", v, v)
if p, ok := v.(*int); ok {
fmt.Println("v holds *int, its value is:", p)
}
输出(在Go Playground上试用):
Type: *int, Value: <nil>
v holds *int, its value is: <nil>
但是请注意,您必须调用Value.Interface()
才能获得reflect.Value
的值(离开反射世界).还要注意,这个返回的接口值(它的类型是interface{}
或any
)将是not是nil
,但它打包了一个*int
类型和一个nil
指针值.详情见Hiding nil values, understanding why Go fails here