My progress in learning the programming language Go from Google in the form of a daily blog

Thursday, June 18, 2015

Day 17 - Using reflection to write into an interface slice

How to use reflection to write into a slice of unknown items inside an unknown struct:

While working on Gorp with Indexes i had to solve the problem of how to write into a slice inside a struct passed as an interface{}. A new struct with the filled slice should be returned. Both the struct and the slice are not known at compile time, i only have the fieldname of the slice passed to me at runtime. After some serious headscratching and reading through the reflection code i luckily found a way to do it.

The basic method is:

Convert the incoming interface i to a reflect.Type t

Dereference until we have a t which is a Struct

Create a new reflect.Value v from the Type t

From v we now can ask for the FieldName of the slice, getting back another reflect.Value s

As we now have the slice s as a reflect.Value, we need to get the slice elements type

From the slice elements type we create a new instance of it (reflect.New)

Write to fields in this newItem using FieldByName (Hardcoded in the example)

Append the newItem to the slice (the set append was the hard part to find out for me)