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?
reflect.New
returns a reflect.Value
that represents a pointer , the pointer itself is not addressable and it's also not what you want to set the value to. What's addressable however is the value to which the pointer points and that's also what you want to set the provided value.
You can use res.Elem()
to dereference the pointer.
func main() {
value := uint64(0x36)
resType := reflect.TypeOf(uint8(0))
expectedRes := uint8(0x36)
res := reflect.New(resType)
setFieldValue(res.Elem(), resType.Kind(), value)
if res.Elem().Interface() == expectedRes {
fmt.Println("voila")
} else {
fmt.Println("nuts")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.