小编wus*_*ain的帖子

使用reflect,如何为结构体字段(指针)设置值

我尝试通过反射将值设置为结构字段(指针字段),但失败了。

  1. 我获取了结构体字段的名称,因此使用 FieldByName 来获取该字段
  2. 该字段是一个指针。
  3. 我尝试使用 FieldByName().Set FieldByName().SetPointer 来设置值。
type t struct {
    b *int
}

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

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

Run Code Online (Sandbox Code Playgroud)

第一个代码: =======> ./test.go:14:50: 无法使用 (type *int) 作为reflect.ValueOf(t).FieldByName("b") 参数中的reflect.Value 类型.Set ./test.go:14:50:reflect.ValueOf(t).FieldByName("b").Set(a) 用作值

第二个代码: =======> ./test.go:14:57:不能使用 (type *int) 作为参数中的类型 unsafe.Pointer 到reflect.ValueOf(t).FieldByName("b") .SetPointer ./test.go:14:57:reflect.ValueOf(t).FieldByName("b").SetPointer(a) 用作值

我想使用 Reflect 来使指针字段(名称“b”)分配一个空间并设置一个值。

go reflect

2
推荐指数
1
解决办法
4944
查看次数

标签 统计

go ×1

reflect ×1