Hi there, I have a struct that contains an unexported map protected by a mutex, let’s say something like:
type Map struct { mtx sync.Mutex col map[string]interface{} } I want to implement a ForEach method that works in O(1) space and doesn’t hold the mutex while working on each entry. This is what I have: func (m *Map) ForEach(fn func(k, v interface{})) { m.mtx.Lock() for k, v := range m.col { m.mtx.Unlock() fn(k, v) m.mtx.Lock() } m.mtx.Unlock() } (runnable example: https://play.golang.org/p/tX2lCCYWxq) The language spec <https://golang.org/ref/spec#For_statements> says: > 3. 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. With the caveats mentioned above regarding concurrent deletions/insertions in mind, is this implementation of ForEach correct? Is there a better way? Thanks. -- Benoit "tsuna" Sigoure -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.