puzpuzpuz / xsync

Concurrent data structures for Go
Apache License 2.0
1.11k stars 38 forks source link

[FEAT REQ] Add Utility Method to Convert `xsync.MapOf` to a Regular Go Map #149

Open KiddoV opened 5 days ago

KiddoV commented 5 days ago

The xsync.MapOf is a concurrent-safe map, but for use cases where a regular map is needed (e.g., serialization or interactions with non-concurrent code), it would be very convenient to have a built-in method for this conversion. This would improve usability and reduce boilerplate code in user applications.

Currently, to convert an xsync.MapOf[K, V] to a regular Go map (map[K]V), I would have to manually iterate over the xsync.MapOf using the Range method, like so:

func xSyncMapToMap[K comparable, V any](x *xsync.MapOf[K, V]) map[K]V {
    goMap := make(map[K]V)
    //
    x.Range(func(key K, value V) bool {
        goMap[key] = value
        return true //Continue iteration
    })
    return goMap
}

It would be helpful if the library could provide a utility method that simplifies this process, such as:

func (m *MapOf[K, V]) ToMap() map[K]V

Is this safe to do? What do you think?

puzpuzpuz commented 5 days ago

Thanks for bringing up the idea. It makes sense to me an enhancement.