-1

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
Ross Bown
  • 89
  • 1
  • 1
  • 11
  • 2
    Don't mutate the map while you're iterating over it. You can change the values but you shouldn't add or remove any items. – Adrian Jan 07 '19 at 18:00
  • Plus if you're trying to modify a *key* in a map, you should rethink your design. As you've seen from having to remove and re-add the item to fake changing the key, map keys are immutable. Maybe you just want a slice of items where each item has field for key? – Adrian Jan 07 '19 at 18:08
  • Do you mean like a struct? Key and Value stored inside? – Ross Bown Jan 07 '19 at 18:49
  • Yes, like a struct. – Adrian Jan 07 '19 at 19:04

1 Answers1

4

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)
Schwern
  • 153,029
  • 25
  • 195
  • 336
  • Thank you so much! Appreciate your help :) I'm now trying to remove a value... and as stated before, you should never mutate the map via a range loop so how would I do it using this method? `if v, ok := data[k]; ok { data[k] = append(data[k][:i], data[k][i+1:]...) fmt.Fprintf(w, "KEY: %v: VALUE: %v was deleted successfully", k, v)` – Ross Bown Jan 07 '19 at 18:46
  • @RossBown It's only the keys you have to worry about. You can change the values all you like. But there's no more iteration here, so you're safe. And it's not clear what you're trying to do there. Ask another question. – Schwern Jan 07 '19 at 18:51
  • I want to delete just one value, from the slice of string in the MAP... do i loop through the values and delete the one which matches the param in the URL... or is there a better way? From what I can see on the docs, there isn't a way to loop through and delete the value via the name of it, but rather you have to find the index, and delete that. – Ross Bown Jan 07 '19 at 18:57
  • @RossBown Removing a value from a slice is a separate problem from changing its key in a map. Ask another question about that. – Schwern Jan 07 '19 at 19:11
  • @RossBown See https://stackoverflow.com/questions/25025409/delete-element-in-a-slice#25025536 – Schwern Jan 07 '19 at 19:16