mp := map[string][]int{
"1" : {1,2,3,4},
}
for _,s := range mp {
i:= 0
for _,v:=range s{
if v%2==0 {
s[i] = v
i++
}
}
s = s[:i]
// I tried mp[k] = s and it works fine
}
want := map[string][]int{
"1" : {2,4},
}
if !reflect.DeepEqual(mp,want) {
fmt.Printf("not expected")
fmt.Println(mp)
}
With the above code I'm not able to remove odd integers from the slice.
I changed this to
mp := map[string][]int{
"1" : {1,2,3,4},
}
for k,s := range mp {
i:= 0
for _,v:=range s{
if v%2==0 {
s[i] = v
i++
}
}
s = s[:i]
mp[k] = s
}
want := map[string][]int{
"1" : {2,4},
}
And now it works. I am wondering what is the problem with the first piece of code. I think s's address is not changed.
for k,s := range mp {
Here s keeps the value of mp, which is []int.
If you change or modify the s in the loop it won't affect the value of mp, cause s is just a copy of the value of mp. If you want to affect the change into mp then modify with mp[k].