You can consider this example:
package maptest
var oldMap = map[string]string{"key1": "old_value1", "key2": "old_value2", "key3": "old_value3"}
func updateMap() {
oldMap = map[string]string{"key1": "new_value1", "key2": "new_value2", "key3": "new_value3"}
}
func action1() string {
return oldMap["key1"]
}
func action2() {
var resultKey string
var resultValue string
for k, v := range oldMap {
resultKey += oldMap[k]
resultValue += v
}
}
- if the updateMap() function is executed in parallel with action1(), will it cause a panic or will action1() just return the old value? Why?
- if the updateMap function is executed while the action2() cycle is running, what will be the result? I'm assuming that getting by key will start accessing the new map, while v will belong to a copy of the old one. Is it so? Is the variant with v safe in this case and guarantees the correct result (data from one map)?