sync: implement sync.Swap

This commit is contained in:
Ayke van Laethem
2025-07-31 13:44:13 +02:00
committed by Ron Evans
parent e368551919
commit d6343d9d5c
2 changed files with 31 additions and 0 deletions
+12
View File
@@ -70,3 +70,15 @@ func (m *Map) Range(f func(key, value interface{}) bool) {
}
}
}
// Swap replaces the value for the given key, and returns the old value if any.
func (m *Map) Swap(key, value any) (previous any, loaded bool) {
m.lock.Lock()
defer m.lock.Unlock()
if m.m == nil {
m.m = make(map[interface{}]interface{})
}
previous, loaded = m.m[key]
m.m[key] = value
return
}