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

标签 go dynamic struct

我是 golang 的新手,正在从 php 迁移到 golang。

我正在尝试做类似下面的事情,我希望从变量测试中分配字段名称 age。这在 golang 中可能吗?

在 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})

 } 

这只是复制我的用例的示例代码。

最佳答案

您有三个选项,大致按优先顺序排列:

1) if/switch 语句:

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

2) 使用映射而不是结构:

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

3) 使用反射。参见 this question有关详细信息,但通常您应该避免反射。它很慢,而且不惯用,而且它只适用于导出的字段(你的例子使用未导出的字段,所以写的,无论如何都不是反射的候选者)。

关于go - 如何从变量分配结构的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51240758/

相关文章:

go - Go 的 bufio.Scanner 中的 "Scan advances the Scanner to the next token"是什么意思?

linux - 如果 block 设备已经格式化,则退出 mkfs 命令

go - 在 golang func 中使用默认值

bash - 启动自定义 init.d 脚本会导致在本地主机上找不到 404 页面

c - 在 C 中将字符串传递给结构体

c - 对于 C 中的结构体,下面的代码意味着什么?

recursion - F# 中的递归序列

html - 具有动态粘性页脚的站点布局,可返回到 IE6,没有 JS : Is it possible?

mysql - 显示第二个表中条目数的动态值

c - 在具有相同类型成员的结构上使用 free