首页 > 解决方案 > 如何从 Golang 中的变量访问结构参数值

问题描述

我正在尝试使用包含属性键的变量访问结构属性。

例如,我得到了这个结构:

type person struct {
    name string
    age  int
}

我有一个包含字符串值“age”的变量“property”。

我想用person.property之类的东西访问年龄?

你认为在 golang 中可能吗?

标签: go

解决方案


如果你正在寻找类似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())
}

推荐阅读