go - 如何在 Go 中按名称设置结构字段的复合字段?
问题描述
我有一个结构,其中一个字段是另一个结构,我想按名称(作为参数)访问这个结构。我跟着Using reflect,你如何设置结构字段的值?它适用于基本类型,但不适用于复合类型。
package main
import (
"fmt"
"reflect"
)
type PntInt struct {
p *int64
}
type Foo struct {
X int64
Px PntInt
}
func main() {
foo := Foo{}
fmt.Println(foo)
i := int64(8)
Pi := PntInt{&i}
reflect.ValueOf(&foo).Elem().FieldByName("X").SetInt(i)
reflect.ValueOf(&foo).Elem().FieldByName("Px").Set(Pi)
fmt.Println(foo)
}
设置整数有效,但尝试设置“Px”失败并出现错误
./prog.go:25:52: cannot use Pi (type PntInt) as type reflect.Value in argument to reflect.ValueOf(&foo).Elem().FieldByName("Px").Set
解决方案
推荐阅读
- gpflow - 泊松的变分期望
- postgresql - 如何使用 PostegreSQL 中另一个表中的所有记录测试新值?
- google-chrome - macbook的chrome本地覆盖错误
- r - R将不同格式的日期转换为单一格式
- laravel - Laravel - 如何导出两个有关系的表
- react-native - 如何使用 @aspnet/signalr 库在 reactnative 中修复“错误:无法启动传输 'WebSockets': null ”?
- vue.js - Vue $watch 用于对象数组
- c# - SpeakSsmlAsync 返回 BadRequest
- excel - 加载行为 3 Excel 加载项在打开文件后加载,在慢速计算机上通过命令行启动时
- tensorflow - 有什么作用?张量形状?