To use sync.Map for efficient concurrent read and write operations on a map in Golang, follow these steps:
Import the sync package: import "sync"
Declare and initialize the sync.Map object: var myMap sync.Map
Use the Store
method to write a value to the map:
myMap.Store(key, value)
Use the Load
method to read a value from the map:
result, ok := myMap.Load(key)
if ok {
// handle value found
} else {
// handle value not found
}
Use the Range
method to iterate over all the key-value pairs in the map:
myMap.Range(func(key, value interface{}) bool {
// handle each key-value pair
return true // return false to stop iteration
})
Use the Delete
method to remove a key-value pair from the map:
myMap.Delete(key)
Note: It's important to remember that sync.Map does not provide direct access to the underlying map. Therefore, you can't use the length function len
on sync.Map. Instead, use the Range
method to iterate or perform any other operations on the map's elements.