Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created October 26, 2022 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/887663c0ae36285b5d6ffd2c2862835f to your computer and use it in GitHub Desktop.
Save mdwhatcott/887663c0ae36285b5d6ffd2c2862835f to your computer and use it in GitHub Desktop.
Like Java's 'computeIfAbsent'...
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