for key := range m {
if expired(key) {
delete(m, key)
}
}
Is it safe to delete from m while iterating through it? That's always
been a big no-no in one of the languages (C#) I'm coming from.
Usually this means I need to create a temporary list of items to
remove and then remove them in another loop. If I don't need to do
that anymore that is great news.
BTW, congrats on Go1, and thanks for the great language :).
-Nate
My understanding is "yes".
From http://golang.org/ref/spec#For_statements --
"The range expression is evaluated once before beginning the loop . .
. If map entries that have not yet been reached are deleted during
iteration, the corresponding iteration values will not be produced."
- Evan
-Nate
given that the spec doesn't say that deleting from the map during
iteration is unsafe (and in fact explicitly mentions a case to
do with deleting when iterating), it *is* necessarily a safe operation.
"The built-in function delete removes the element with key k from a map m."
no caveats.
> Yes, it's safe: http://weekly.golang.org/ref/spec#For_statements
Is it thread-safe, too? When one go routine is iterating over the map,
and another one is deleting from it?
Norbert
Is it thread-safe, too? When one go routine is iterating over the map,
and another one is deleting from it?
No, it's not. Reading from multiple goroutines is fine, but if one
wants to write you need to synchronize somehow.
- Evan