I want to test how my function setFieldValue()
works.
func main() {
value := uint64(0x36)
resType := reflect.TypeOf(uint8(0))
expectedRes := uint8(0x36)
res := uint8(0)
setFieldValue(reflect.ValueOf(&res).Elem(), resType.Kind(), value)
if res == expectedRes {
fmt.Println("voila")
} else {
fmt.Println("nuts")
}
}
func setFieldValue(field reflect.Value, fieldKind reflect.Kind, fieldValue uint64) {
switch fieldKind {
case reflect.Uint8:
field.SetUint(fieldValue)
}
}
But I don't want res
variable also has type TypeOf(uint8(0))
. If I create res as
res := reflect.New(resType)
setFieldValue(res, resType.Kind(), value)
it doesn't work because res is unaddressable.
What is the correct way to create variable using reflect and then to set its value in some func?
Or how can I get the instance of newly created variable?
Aucun commentaire:
Enregistrer un commentaire