【发布时间】:2020-04-30 19:04:43
【问题描述】:
我想测试我的函数setFieldValue() 是如何工作的。
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)
}
}
但我不希望res 变量也具有TypeOf(uint8(0)) 类型。如果我将 res 创建为
res := reflect.New(resType)
setFieldValue(res, resType.Kind(), value)
它不起作用,因为 res 无法寻址。
使用反射创建变量然后在某些函数中设置其值的正确方法是什么?
或者如何获取新创建的变量的实例?
【问题讨论】:
标签: go reflection