我尝试通过反射将值设置为结构字段(指针字段),但失败了。
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”)分配一个空间并设置一个值。
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)
}
Run Code Online (Sandbox Code Playgroud)
游乐场https://play.golang.org/p/gZt0ahTZMIi
| 归档时间: |
|
| 查看次数: |
4944 次 |
| 最近记录: |