go - 如何从 Golang 中的变量访问结构参数值
问题描述
我正在尝试使用包含属性键的变量访问结构属性。
例如,我得到了这个结构:
type person struct {
name string
age int
}
我有一个包含字符串值“age”的变量“property”。
我想用person.property之类的东西访问年龄?
你认为在 golang 中可能吗?
解决方案
如果你正在寻找类似person[property]
Python 或 JavaScript 的东西,答案是否定的,Golang 不支持在运行时动态选择字段/方法。
但是你可以这样做reflect
:
import (
"fmt"
"reflect"
)
func main() {
type person struct {
name string
age int
}
v := reflect.ValueOf(person{"Golang", 10})
property := "age"
f := v.FieldByName(property)
fmt.Printf("Person Age: %d\n", f.Int())
}
推荐阅读
- python - FileNotFoundError: [WinError 3] 系统找不到指定的路径:''
- python - 使用漂亮的汤在 div 标签下抓取网页
- python - FBChat 和 python 不能发送简单的消息
- c - 在终端中出现错误 `\365\277\357\376
- java - 如何在 ContextRefreshEvent 之后运行 @Configuration?
- influxdb - 我们如何从灯塔轮询数据到 InfluxDB 或 Graphite 以在 Grafana 中可视化它
- xml - 结合使用两个 XSLT key() 函数
- javascript - NodeJS:在循环中查询 MS SQL 会冻结响应
- android - 从主模块访问动态功能模块的可绘制文件夹中的图形
- python - python中的read()和readline()有什么区别?