Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflect, how do you initialize value of a struct pointer field?

Tags:

go

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

like image 905
slene Avatar asked May 09 '13 06:05

slene


2 Answers

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())
like image 156
ANisus Avatar answered Nov 02 '22 23:11

ANisus


try this

var i int
f.Set(reflect.ValueOf(&i))
like image 2
Arne Avatar answered Nov 02 '22 22:11

Arne