使用反射,如何初始化结构体指针字段的值?

huangapple go评论134阅读模式
英文:

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

how to set the *D to default value use reflect

英文:
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

how to set the *D to default value use reflect

答案1

得分: 13

你需要一个指针值(*int),但是reflect文档中对于func Zero(typ Type) Value的说明是:
>返回的值既不可寻址也不可设置。

在你的情况下,你可以使用New代替:

z := reflect.New(f.Type().Elem())
英文:

You need to have a pointer value (*int), but the reflect documentation states for func Zero(typ Type) Value that:
>The returned value is neither addressable nor settable.

In your case you can instead use New:

z := reflect.New(f.Type().Elem())

答案2

得分: 2

尝试一下

var i int
f.Set(reflect.ValueOf(&i))
英文:

try this

var i int
f.Set(reflect.ValueOf(&i))

huangapple
  • 本文由 发表于 2013年5月9日 14:51:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/16456098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定