patterngoCritical
Is it safe to remove selected keys from map within a range loop?
Viewed 0 times
fromkeysremoveselectedsaferangeloopwithinmap
Problem
How can one remove selected keys from a map?
Is it safe to combine
https://play.golang.org/p/u1vufvEjSw
Is it safe to combine
delete() with range, as in the code below?package main
import "fmt"
type Info struct {
value string
}
func main() {
table := make(map[string]*Info)
for i := 0; i %v\n", key, value.value)
delete(table, key)
}
}https://play.golang.org/p/u1vufvEjSw
Solution
This is safe! You can also find a similar sample in Effective Go:
And the language specification:
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.
for key := range m {
if key.expired() {
delete(m, key)
}
}And the language specification:
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If map entries that have not yet been reached are removed during iteration, the corresponding iteration values will not be produced. If map entries are created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.
Code Snippets
for key := range m {
if key.expired() {
delete(m, key)
}
}Context
Stack Overflow Q#23229975, score: 301
Revisions (0)
No revisions yet.