douerqu2319 2019-07-22 12:42
浏览 134

使用反射,如何将值设置为结构字段(指针)

I try to set value to a struct field (pointer field) by reflect, but failed.

  1. I get the name of a struct field, so use FieldByName to get the field
  2. The field is a pointer.
  3. I try to use FieldByName().Set FieldByName().SetPointer to set value.
type t struct {
    b *int
}

func main() {
    t := new(ts)
    a := new(int)
    ss := reflect.ValueOf(t).FieldByName("b").Set(a)
}
type t struct {
    b *int
}

func main() {
    t := new(ts)
    a := new(int)
    ss := reflect.ValueOf(t).FieldByName("b").SetPointer(a)
}

First code: =======> ./test.go:14:50: cannot use a (type *int) as type reflect.Value in argument to reflect.ValueOf(t).FieldByName("b").Set ./test.go:14:50: reflect.ValueOf(t).FieldByName("b").Set(a) used as value

Second code: =======> ./test.go:14:57: cannot use a (type *int) as type unsafe.Pointer in argument to reflect.ValueOf(t).FieldByName("b").SetPointer ./test.go:14:57: reflect.ValueOf(t).FieldByName("b").SetPointer(a) used as value

I want to use reflect to make the pointer field (name "b") alloced a space and set a value.

  • 写回答

1条回答 默认 最新

  • dongtang6681 2019-07-22 13:15
    关注
    type ts struct {
        B *int    //field must be exported
    }
    
    func main() {
        var t ts
        foo := 5
        a := &foo
        //Use Elem() to indirect through the pointer and get struct field
        //Use reflect.ValueOf(a) to satisfy Set() signature
        reflect.ValueOf(&t).Elem().FieldByName("B").Set(reflect.ValueOf(a))
        fmt.Println(*t.B)
    }
    

    Playground https://play.golang.org/p/gZt0ahTZMIi

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法