percy
percy

Reputation: 1118

reflection - get type of single slice element

I want to iterate over struct definition recursively and for slices get a type of a singular element. Then, create an empty instance of that type. For example:

type Path struct {
  Name string
  Points []Coordinate
}
type Coordinate struct {
  Latitude float64
  Longitude float64
}

Assuming that types are unknown at runtime, how can I create an empty instance of the nested type (in the above example Coordinate). I mean:

x := Coordinate{}

When at input I get Path (which can be any other struct, with slices of different types)?

Upvotes: 4

Views: 2290

Answers (1)

icza
icza

Reputation: 417512

If you have the reflect.Type descriptor of some value, you may use reflect.New() function to obtain a pointer to a new, zeroed value.

This will return you a reflect.Value value. This will be a pointer, to get the reflect.Value of the pointed object, use Value.Elem(). To "unwrap" the value held inside reflect.Value(), you may use Value.Interface().

So if you have a reflect.Type descriptor of a slice, you may use Type.Elem() to get the reflect.Type descriptor of the element type of the slice.

See this example:

p := Path{
    Name: "foo",
    Points: []Coordinate{
        {1.1, 2.2},
        {3.3, 4.4},
    },
}

v := reflect.ValueOf(p)
f := v.FieldByName("Points")

cv := reflect.New(f.Type().Elem()).Elem()
c := cv.Interface()
fmt.Printf("%#v\n", c)

This outputs (try it on the Go Playground):

main.Coordinate{Latitude:0, Longitude:0}

Upvotes: 7

Related Questions