dsag14654 2019-01-07 17:57
浏览 18
已采纳

更新地图中的键,同时遍历该地图

I want to update the key from one name to another using URL params. I have the code, but the output is incorrect. See below.

This is the map

var data map[string][]string

The PUT method for the function im calling

r.HandleFunc("/updatekey/{key}/{newkey}", handleUpdateKey).Methods("PUT")

The handleUpdateKey func, which is noted up explaining exactly what it's doing.

func handleUpdateKey(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)

k := params["key"] //get url params
nk := params["newkey"]

s := make([]string, len(data[k])) //create slice of string to store map variables
for i := range data {             //range over the data map
    fmt.Fprintf(w, i)
    if k != i { //check if no keys exist with URL key param
        fmt.Fprintf(w, "That KEY doesn't exist in memory")
        break //kill the loop
    } else { //if there is a key the same as the key param
        for _, values := range data[i] { //loop over the slice of string (values in that KEY)
            s = append(s, values) //append all those items to the slice of string
        }

        delete(data, k) //delete the old key

        for _, svalues := range s { //loop over the slice of string we created earlier
            data[nk] = append(data[nk], svalues) //append the items within the slice of string, to the new key... replicating the old key, with a new key name
        }
    }
}
}

The below should assign all the values of that KEY to a slice of string, which we later iterate over and add to the new KEY. This works, however, the output is as below which is clearly incorrect

KEY: catt: VALUE: 
KEY: catt: VALUE: 
KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena

OLD OUTPUT:

KEY: dog: VALUE: zeus
KEY: dog: VALUE: xena

CORRECT NEW OUTPUT:

KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena
  • 写回答

1条回答 默认 最新

  • douxie7339 2019-01-07 18:08
    关注

    In most languages, altering a structure you're iterating over will cause strange things to happen. Particularly maps. You have to find another way.

    Fortunately there's no need to iterate at all. Your loop is just one big if/else statement. If the key matches, do something. If it doesn't, do something else. Since this is a map, there's no need to search for the key using iteration, it can be looked up directly. There's also no need for all that laborious looping just to copy a map value.

    if val, ok := data[k]; ok {
        // Copy the value
        data[nk] = val
        // Delete the old key
        delete(data, k)
    } else {
        fmt.Fprintf(w, "The key %v doesn't exist", k)
    }
    

    Finally, avoid using globals in functions. It makes it difficult to understand what effect a function has on the program if it can change globals. data should be passed in to the function to make it clear.

    func handleUpdateKey(w http.ResponseWriter, r *http.Request, data map[string][]string)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看