How to update map values in Go

前端 未结 1 1514
失恋的感觉
失恋的感觉 2020-11-29 10:22

I want to build a map with string key and struct value with which I\'m able to update struct value in the map identified by map key.

I\'ve tried this and this which

相关标签:
1条回答
  • 2020-11-29 10:38

    You can't change values associated with keys in a map, you can only reassign values.

    This leaves you 2 possibilities:

    1. Store pointers in the map, so you can modify the pointed object (which is not inside the map data structure).

    2. Store struct values, but when you modify it, you need to reassign it to the key.

    1. Using pointers

    Storing pointers in the map: dataManaged := map[string]*Data{}

    When you "fill" the map, you can't use the loop's variable, as it gets overwritten in each iteration. Instead make a copy of it, and store the address of that copy:

    for _, v := range dataReceived {
        fmt.Println("Received ID:", v.ID, "Value:", v.Value)
        v2 := v
        dataManaged[v.ID] = &v2
    }
    

    Output is as expected. Try it on the Go Playground.

    2. Reassigning the modified struct

    Sticking to storing struct values in the map: dataManaged := map[string]Data{}

    Iterating over the key-value pairs will give you copies of the values. So after you modified the value, reassign it back:

    for m, n := range dataManaged {
        n.Value = "UpdatedData for " + n.ID
        dataManaged[m] = n
        fmt.Println("Data key:", m, "Value:", n.Value)
    }
    

    Try this one on the Go Playground.

    0 讨论(0)
提交回复
热议问题