title: Traverse struct with reflect, create new slice of pointer type with reflect
body: <p>Context: I'm trying to take any <code>struct</code>, and fill it with random data.</p>
  
  <p>My big sticking point at the moment is that if a <code>struct</code> has a field that is a slice with a pointer type (ie. <code>[]*Foo</code>), I'm unable to figure out how to create data for that struct using reflection.</p>
  
  <p>Here's what my function currently looks like:</p>
  
  <pre class="lang-golang prettyprint-override"><code>func randFill(in interface{}) interface{} {
      t := reflect.TypeOf(in)
      v := reflect.ValueOf(in)
  
      if v.Kind() == reflect.Ptr {
          v = v.Elem()
      }
  
      switch v.Kind() {
      case reflect.Struct:
          newStr := reflect.New(t).Elem()
          for i := 0; i &lt; t.NumField(); i++ {
              newV := randFill(reflect.New(t.Field(i).Type).Interface())
              newStr.Field(i).Set(reflect.ValueOf(newV))
          }
  
          return newStr.Interface()
      case reflect.Slice:
          num := rand.Intn(10)
          slice := reflect.MakeSlice(v.Type(), num, num)
  
          for j := 0; j &lt; num; j++ {
              newC := slice.Index(j)
              if newC.Kind() == reflect.Ptr {
                  ncInt := reflect.New(newC.Type())
                  newC = ncInt.Elem()
              }
              gen := randFill(newC.Interface())
              slice.Index(j).Set(reflect.ValueOf(gen))
          }
  
          return slice.Interface()
      //
      // ... there are other cases down here for handling primitives
      //
      }
  
      return nil
  }
  </code></pre>
  
  <p>This works great on a slice without pointer types, but here's an example of some structs that it has trouble with:</p>
  
  <pre class="lang-golang prettyprint-override"><code>type Parent struct {
      Name     string
      Age      int
      Children []*Child
  }
  
  type Child struct {
      Name string
      Age  int
  }
  </code></pre>
  
  <p>Where if I created a <code>Parent{}</code> and passed it into <code>randFill(Parent{})</code>, it has trouble generating values for <code>*Child</code> because when it gets to this line:</p>
  
  <pre class="lang-golang prettyprint-override"><code>newC := slice.Index(j)
  </code></pre>
  
  <p>The value of <code>newC</code> at this point, when handling the slice of <code>[]*Child</code> is <code>(*Child)(nil)</code>, and it's a <code>reflect.Value</code> type.</p>
  
  <pre class="lang-golang prettyprint-override"><code>newC := slice.Index(j)
  fmt.Printf("%#v, %T", newC, newC) // Outputs: (*Child)(nil), reflect.Value
  </code></pre>
  
  <p>There's something I'm missing around being able to initialize a pointer type, from a <code>reflect.Value</code>, or I've created the incorrect type of slice, and that is the root of my problems?</p>