[英]Using reflect, how do you initialize value of a struct pointer field?
package main
import (
"fmt"
"reflect"
)
type A struct {
D *int
}
func main() {
a := &A{}
v := reflect.ValueOf(a)
e := v.Elem()
f := e.Field(0)
z := reflect.Zero(f.Type().Elem())
f.Set(z)
fmt.Println(z)
}
panic: reflect.Set: value of type int is not assignable to type *int panic:reflect.Set:int类型的值不能赋值为* int
how to set the *D to default value use reflect 如何将* D设置为默认值使用反射
You need to have a pointer value (*int), but the reflect
documentation states for func Zero(typ Type) Value
that: 你需要有一个指针值(* int),但是
reflect
文档说明了func Zero(typ Type) Value
:
The returned value is neither addressable nor settable.
返回的值既不可寻址也不可设置。
In your case you can instead use New
: 在您的情况下,您可以改为使用
New
:
z := reflect.New(f.Type().Elem())
try this 试试这个
var i int
f.Set(reflect.ValueOf(&i))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.