-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: maps: add a SafeInsert function for the common case of checking a map for existence before inserting #70707
Comments
Related Issues (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
Not even discussing if this is a problem that needs a fix. // SafeInsert first creates the map if it is nil, then inserts 'v' into the map at key 'k'.
func SafeInsert[Map ~map[K]V, K comparable, V any](m Map, k K, v V) Map |
No, the original suggestion would work. var m map[string]int // &m will be a non-nil pointer to a nil map.
maps.SafeInsert(&m, "example", 3) I do think that the |
I get why this would be bundled with insert but I think that would look odd when there are multiple inserts as only the first would be the Safe variety. Either version could just ensure a non-nil map: func X[Map ~map[K]V, K comparable, V any](m *Map) {
if *m == nil {
*m = Map{}
}
}
// or
func X[Map ~map[K]V, K comparable, V any](m Map) Map {
if m == nil {
return Map{}
}
return m
} though with #12854 that line of code is just if m == nil {
m = {}
}
|
I agree but then you have to make sure you give it a non-nil |
I figured that map pointer variables are pretty rare and unusual so callers are unlikely to make the mistake of passing in a nil pointer and will instead use '&myMap' which will never be nil. "rare and unusual" is not "always" though 😄 The |
Proposal Details
When inserting into a map
m
that may be nil the following kind of snippet is needed:It would be nice if the
maps
package included a generic function to simplify this to one line.I'd imagine there is a better name for this sort of function, but here is what the implementation could be:
This could then be used like:
https://go.dev/play/p/sMRAojtakEu
The text was updated successfully, but these errors were encountered: