12
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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
slene
  • 121
  • 2
  • 3
  • `D` is a pointer, which starts out `nil`. It doesn't point anywhere, so it doesn't make sense to "set the *D" – newacct May 10 '13 at 10:27

2 Answers2

13

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())
ANisus
  • 74,460
  • 29
  • 162
  • 158
2

try this

var i int
f.Set(reflect.ValueOf(&i))
Arne
  • 7,921
  • 9
  • 48
  • 66