LoadOrStore returns the existing value for key if present; otherwise it stores and returns value. The loaded result is true if the value was loaded, false if stored.
(key K, value V)
| 52 | // stores and returns value. The loaded result is true if the value was |
| 53 | // loaded, false if stored. |
| 54 | func (m *Map[K, V]) LoadOrStore(key K, value V) (V, bool) { |
| 55 | m.mu.RLock() |
| 56 | if existing, ok := m.values[key]; ok { |
| 57 | m.mu.RUnlock() |
| 58 | return existing, true |
| 59 | } |
| 60 | m.mu.RUnlock() |
| 61 | |
| 62 | m.mu.Lock() |
| 63 | defer m.mu.Unlock() |
| 64 | |
| 65 | // Re-check under the write lock: another goroutine may have stored |
| 66 | // the key between releasing the read lock and acquiring the write lock. |
| 67 | if existing, ok := m.values[key]; ok { |
| 68 | return existing, true |
| 69 | } |
| 70 | if m.values == nil { |
| 71 | m.values = make(map[K]V) |
| 72 | } |
| 73 | m.values[key] = value |
| 74 | return value, false |
| 75 | } |
| 76 | |
| 77 | // Clear removes all entries from the map. |
| 78 | func (m *Map[K, V]) Clear() { |