Created
October 26, 2022 04:48
-
-
Save mdwhatcott/887663c0ae36285b5d6ffd2c2862835f to your computer and use it in GitHub Desktop.
Like Java's 'computeIfAbsent'...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func GetOrSetDefault[K comparable, V any](m map[K]V, key K, new_ func() V) V { | |
value, found := m[key] | |
if !found { | |
value = new_() | |
m[key] = value | |
} | |
return value | |
} | |
/* | |
a := make(map[int]string) | |
GetOrSetDefault(a, 42, func() string { return "hi" }) | |
fmt.Println(a[42]) // hi | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment