struct - 您可以将结构字段名传递给 golang 中的函数吗?

标签 struct types go func

例如,假设您有类似的东西,尽量使示例尽可能简单。

type Home struct {
    Bedroom string
    Bathroom string
}

如何将字段名称传递给函数?

func (this *Home) AddRoomName(fieldname, value string) {
    this.fieldname = value
}

显然那是行不通的......我能看到的唯一方法是使用两个函数,当结构变得非常大并且有很多相似的代码时,这两个函数会添加很多额外的代码。

func (this *Home) AddBedroomName(value string) {
    this.Bedroom = value
}
func (this *Home) AddBathroomName(value string) {
    this.Bathroom = value
}

最佳答案

我知道的唯一方法是使用反射:

func (this *Home) AddRoomName(fieldname, value string) {
    h := reflect.ValueOf(this).Elem()
    h.FieldByName(fieldname).Set(reflect.ValueOf(value))
    return
}

http://play.golang.org/p/ZvtF_05CE_

关于struct - 您可以将结构字段名传递给 golang 中的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30787453/

相关文章:

go - 在 Go 中将字符串转换为固定大小的字节数组

regex - 正则表达式在两组中至少执行一个

arrays - 是否可以在 Matlab 中将结构体转换为映射?

C++ 类型名作为变量

mysql - mysql中的float精度问题

go - 如何从http响应中提取某个 header [Set-Cookie]

c++ - 当多维数组是结构的属性时,如何通过引用传递它?

c - MPI 结构错误

c - C 中的结构体定义?

haskell - 是否可以使 Traversal 成为 IsString 的实例