go - 使用反射,如何将值设置为结构字段(指针)
问题描述
我尝试通过反射将值设置为结构字段(指针字段),但失败了。
- 我得到了一个结构字段的名称,所以使用 FieldByName 来获取该字段
- 该字段是一个指针。
- 我尝试使用 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)
}
type t struct {
b *int
}
func main() {
t := new(ts)
a := new(int)
ss := reflect.ValueOf(t).FieldByName("b").SetPointer(a)
}
第一个代码:=======> ./test.go:14:50: 不能在 reflect.ValueOf(t).FieldByName("b") 的参数中使用 a (type *int) 作为类型 reflect.Value .Set ./test.go:14:50: reflect.ValueOf(t).FieldByName("b").Set(a) 用作值
第二个代码:=======> ./test.go:14:57: 不能使用 a (type *int) 作为类型 unsafe.Pointer 在参数中以 reflect.ValueOf(t).FieldByName("b") .SetPointer ./test.go:14:57: reflect.ValueOf(t).FieldByName("b").SetPointer(a) 用作值
我想使用反射使指针字段(名称“b”)分配一个空间并设置一个值。
解决方案
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)
}
推荐阅读
- c - 在 Xcode 中编译时出现全局变量错误(C 编程)
- forms - 带有多个按钮的 react-jsonschema-form
- javascript - 无法使随机图像显示 javascript
- debian - 如何获取 debian 软件包的 *.changes 文件?
- json - Angular 4 在表格中显示 json
- php - 提交html表单时替换php变量
- python - Tensorflow 连接未指定形状的张量
- hibernate - JPA:未从父主键插入外键
- python - 使用较小的日期范围和列值过滤较大的 DataFrame
- html - django 静态文件在直播时不会更新