mercredi 18 février 2015

Set an interface on a struct field golang

Is there any way to set an interface field using reflect? When i tried to set it, it paniced saying that the value is non addressable.



type A interface{...}

func CreateA(name string) A {...}

type B struct {
field A
should A
mirror A
}

// normal way of initializing
var b = B{
field: CreateA("field"),
should: CreateA("should"),
mirror: CreateA("mirror"),
}

func MirrorField(b *B) {
t := reflect.TypeOf(b)
v := reflect.ValueOf(b)
for i := 0; i < t.NumField(); i++ {
setTo = CreateA(t.Field(1).Name)
fieldVal := v.Field(i)
fieldVal.Set(reflect.ValueOf(setTo))
}
}

// what i want is something like
var b = &B{}
MirrorField(b)





Aucun commentaire:

Enregistrer un commentaire