Files
go_goutils/mapsx/funcs.go
T
brent saner 5108b09df5 v1.16.13
ADDED:
* mapsx:
** ListKeys()
** ListValues()
2026-07-15 19:04:00 -04:00

96 lines
1.9 KiB
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
}
/*
ListKeys returns map `m`'s keys as a slice (unlike [maps.Keys],
which returns an iterator via [iter.Seq]).
ListKeys will return nil if `m` is nil, and an empty slice
if `m` is non-nil but empty.
The ordering of `mapKeys` is unpredictable as maps are unsorted
and no explicit sorting is performed.
*/
func ListKeys[Map ~map[K]V, K comparable, V any](m Map) (mapKeys []K) {
var k K
if m == nil {
return
}
mapKeys = make([]K, 0, len(m))
for k, _ = range m {
mapKeys = append(mapKeys, k)
}
return
}
/*
ListValues returns map `m`'s values as a slice (unlike [maps.Values],
which returns an iterator via [iter.Seq]).
ListValues will return nil if `m` is nil, and an empty slice
if `m` is non-nil but empty.
The ordering of `mapVals` is unpredictable as maps are unsorted
and no explicit sorting is performed.
*/
func ListValues[Map ~map[K]V, K comparable, V any](m Map) (mapVals []V) {
var v V
if m == nil {
return
}
mapVals = make([]V, 0, len(m))
for _, v = range m {
mapVals = append(mapVals, 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
}