在给定字段名称和值的映射的情况下修改结构值

时间:2018-05-09 13:50:06

标签: go

这是我的结构:

type TableFields struct {
    Name   string
    Family string
    Age    int
}

sample := TableFields{
    Name:   "bill",
    Family: "yami",
    Age:    25,
}

这是一个非常简单的示例,我用来描述我的问题。

我想使用我收到的sample中的键和值来更改map结构中的值。每次收到map时,键和值都会有所不同。如何使用map编辑sample结构?

例如:

updateTheseFieldsWithTheseVals := make(map[string]string)
updateTheseFieldsWithTheseVals["family"] = "yamie"
// this is my way
for key,val := range updateTheseFieldsWithTheseVals {
    // sample.Family=yamie works, but is not the answer I am looking for
    // sample.key = val  *This solution is not possible*
    oldValue := reflect.Indirect(reflect.ValueOf(get)).FieldByName(key).String()
    fmt.Println(oldValue) // result is yami

    oldValue = val
    fmt.Println(oldValue) //result is yamie
}
fmt.Println(updateTheseFieldsWithTheseVals)
// result :
// {bill yami 25}

这会运行,但不会更改sample中的值。

1 个答案:

答案 0 :(得分:5)

这是一个按名称更新字符串字段的函数:

updates := map[string]string{"Family": "yamie"}
sample := TableFields{
    Name:   "bill",
    Family: "yami",
    Age:    25,
}
update(&sample, updates)

像这样使用:

update

playground example

关于该功能的一些注意事项:

  • fv.IsValid()函数需要一个指针值,以便它可以更新原始值。
  • 如果找不到字段或字段不是字符串类型,函数将会发生混乱。根据功能的使用方式,添加fv.Kind() == reflect.String和{{1}}的检查可能会有所帮助。