I can offer decomposition of map to 2 slices example:
func decomposeMap(m map[string]int) ([]string, []int) {
var i uint
l := len(m)
keys, values := make([]string, l), make([]int, l)
for keys[i], values[i] = range m {
i++
}
return keys, values
}
but I am failing to write map copying:
func copyMap(m map[string]int) map[string]int {
m2 := make(map[string]int, len(m))
for id, m2[id] = range m {} // error - id is not declared
for id, m2[id] := range m {} // error with m2[id] already declared
// id should not be accessible here, it should exist only inside loop
return m2
}
I can declare id as a var, but I dont want it to be available outside for loop. How can i mix assigment and declaration, eg: for id:=, m[id]= range m {}
?
So it will declare index just inside for loop, and will be not accessible outside?
for k, v := range m {}
.v
will be the value associated withk
key. Thefor
loop makes the lookup, not you. Or if you want to, you may dofor k := range m { v := m[k] }
for k, v := range m { m2[k] = v }
v := m[k]
and thenm2[k] = v
. if thisv
is a struct it will be copied over twice. 1) from mapm
to temp bufferv
, and then 2) from temp bufferv
to second mapm2
. I want to avoid that. examplevar id string; for id, m2[id] = range m {}
but here id is declared outside for loop and will remain afterwards you run the loop