简体   繁体   English

如何从变量分配结构的字段名称

[英]How to assign field name of struct from variable

I am new to golang and migrating from php to golang. 我是golang的新手,正在从php迁移到golang。

I am trying to do something like below stuff, where I want field name age to get assigned from variable test. 我正在尝试做下面的事情,我想从变量测试中分配字段名age Is this possible in golang? golang有可能吗?

In php, we have provision like $$test, looking something similar in golang as well. 在php中,我们有类似$$ test之类的规定,在golang中也看起来类似。

 package main
 import "fmt"
 // This `person` struct type has `name` and `age` fields.
 type person struct {
   name string
   age  int
 }

 func main() {

   var test = "age"     
   fmt.Println(person{name: "Alice",test: 30})

 } 

This is just sample code replicating my use case. 这只是复制我的用例的示例代码。

You have three options, in rough order of preference: 您有三种选择,按优先顺序排列:

1) An if/switch statement: 1)if / switch语句:

var p = &person{}
if key == "age" {
    p.age = value
}

2) Use a map instead of a struct: 2)使用映射代替结构:

var p = map[string]interface{}
p[key] = value

3) Use reflection. 3)使用反射。 See this question for details, but generally you should avoid reflection. 有关详细信息,请参见此问题 ,但通常应避免反思。 It's slow, and non-idiomatic, and it only works with exported fields (your example uses un-exported fields, so as written, is not a candidate for reflection anyway). 它很慢,而且很惯用,并且仅适用于导出的字段(您的示例使用未导出的字段,正如所写的那样,无论如何都不适合进行反射)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM