【问题标题】:How to create and set primitive in Golang using reflect如何使用反射在 Golang 中创建和设置原语
【发布时间】: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


    【解决方案1】:

    reflect.New 返回一个代表指针reflect.Value,该指针本身不可寻址,而且它也是不是您想要设置的值。然而,可寻址的是指针指向的值,这也是您想要设置所提供值的值。

    您可以使用res.Elem() 取消引用指针。

    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")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2021-12-26
      相关资源
      最近更新 更多