44 lines
903 B
Go
44 lines
903 B
Go
package mapsx
|
|
|
|
/*
|
|
Get mimics Python's [dict.get()] behavior, returning value `v` if key `k`
|
|
is not found in map `m`.
|
|
|
|
See also [GetOk], [Must].
|
|
|
|
[dict.get()]: https://docs.python.org/3/library/stdtypes.html#dict.get
|
|
*/
|
|
func Get[Map ~map[K]V, K comparable, V any](m Map, k K, v V) (val V) {
|
|
|
|
val, _ = GetOk(m, k, v)
|
|
|
|
return
|
|
}
|
|
|
|
// GetOk is like [Get] but also explicitly indicates whether `k` was found or not. See also [Must].
|
|
func GetOk[Map ~map[K]V, K comparable, V any](m Map, k K, v V) (val V, found bool) {
|
|
|
|
if val, found = m[k]; !found {
|
|
val = v
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
/*
|
|
Must, unlike [Get] or [GetOk], requires that `k` be in map `m`.
|
|
|
|
A panic with error [ErrNotFound] will be raised if `k` is not present.
|
|
Otherwise the found value will be returned.
|
|
*/
|
|
func Must[Map ~map[K]V, K comparable, V any](m Map, k K) (val V) {
|
|
|
|
var ok bool
|
|
|
|
if val, ok = m[k]; !ok {
|
|
panic(ErrNotFound)
|
|
}
|
|
|
|
return
|
|
}
|