douduan5086 2018-05-09 13:50
浏览 80
已采纳

给定字段名称和值的映射,修改结构值

This is my struct:

type TableFields struct {
    Name   string
    Family string
    Age    int
}

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

This is a very simple sample that I am using to describe my problem.

I want to change values in the sample struct using keys and values in a map that I receive. Each time I receive the map the keys and values will be different. How can I use the map to edit the sample struct?

For example:

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}

This runs but does not change the values in sample.

  • 写回答

1条回答 默认 最新

  • dongwuwu6104 2018-05-09 14:01
    关注

    Here's a function that updates string fields by name:

    func update(v interface{}, updates map[string]string) {
        rv := reflect.ValueOf(v).Elem()
        for key, val := range updates {
            fv := rv.FieldByName(key)
            fv.SetString(val)
        }
    }
    

    Use it like this:

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

    playground example

    Some notes about the function:

    • The update function expects a pointer value so it can update the original value.
    • The function will panic if the field is not found or the field is not a string type. Depending on how the function is used, it may be helpful to add checks for fv.IsValid() and fv.Kind() == reflect.String.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题