-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: maps: add CloneOrMake function #69469
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
Comments
Related Issues and Documentation
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
What if it were package maps
// Init returns a new empty map if m is nil, otherwise it returns m.
func Init[Map ~map[K]V, K comparable, V any](m Map) Map {
if m == nil {
return make(M)
}
return m
} If you need a clone, do It is fairly common if you write a type that has a private map to just do |
I did a quick search of just golang/go for |
Thanks for the search. I think slices are different, usually it needs |
For slices, you can do |
Yeah, I just got bit by this last week, but I'm not sure a CloneOrMake function is a solution: if you know about the hazard, you know to call: m2 := make(M2)
maps.Copy(m2, m1) and if you don't know about the hazard, you're going to call Clone anyway. |
I like this idea, closing this because it seems nobody wants a CloneOrMake. |
Proposal Details
I propose
CloneOrMake
function to the maps package.I found it useful when I need a cloned map which should be non-nil. See recent commit 77e42fd.
If this proposal is accepted, we can omit nil-checks and make the code simpler.
This kind of use case is not rare, another evidence is cloneOrMakeHeader:
go/src/net/http/clone.go
Lines 115 to 121 in 3d33437
The text was updated successfully, but these errors were encountered: