Reflect set array to field

Hi everyone

I’m writing a small ORM library. In there I have to set child-models to an array of the parent model generically. I don’t know the types of the models in the library.

What I have:
I have the parent model as type any / interface{}
I have an array of child models as type []any / []interface{}

What I try to do:
I get the reflect.Field of the parent model (works)
I convert the child array to a value with reflect.ValueOf(children)
I want to set the value with field.SetValue()

I get the error reflect.Set: value of type []interface {} is not assignable to type []mod.Person
(Person is my child model in that case)

How could I achieve this?

You’ll need to invoke ArrayOf and populate that array with the elements from your []interface{}. You will find (or already have found) that reflection is a pain. Can you require the model types to implement an interface that you define?

1 Like

i ended up using reflect.Append

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.