jeudi 21 septembre 2017

Set the value of a struct field with reflection when the field is a pointer-to-x

I've checked quite a lot of reflect questions and I've used it quite a bit now but I've not found a solution for this.

Basically, I have a struct of pointers to various primitives. The struct is a config for an application and the reason the fields are pointers is so I can determine between a field set to the default and a field that hasn't been set at all - to enforce "required" fields.

I'll link the source code at the end but lets use a simple example for now:

type Config struct {
    A *string
    B *int
    C *bool
    D *[]string // wildcard!
}

So I grab the reflect.Value via reflect.ValueOf(*cfg) which gives me a .Field on each element, which I iterate through.

The thing is, each element doesn't pass CanAddr or CanSet, I can't seem to find a way to set the value held behind the pointer. Is this a limitation of the language? Will I need to make my fields non-pointers? That would suck as there would be no way to determine if a user specified an empty string or just didn't set it at all for example.

Oh and bonus points for setting/appending a []string field! That one confused me even without pointers thrown in the mix!

Anyway, the relevant code is here: http://ift.tt/2xlcEzZ





Aucun commentaire:

Enregistrer un commentaire