collect is a little Go library which allows to conveniently convert slices into maps in certain ways.
A slice []T
can be converted into:
map[T]bool
with optional key funcmap[T]struct{}
with optional key func (more memory-efficient thanmap[T]bool
on large maps, but less convenient syntactically)map[T]V
with a key-value func
This package does not contain any common "utility" or "helper" functions for maps and slices themselves, since it has a different purpose, only the functions described above.
For full documentation see pkg.go.dev.
map[T]struct{}
uses slightly less memory compared to map[T]bool
, but less readable and convenient to use.
No benchmarks yet, but here's
an article on this topic,
which states the following:
map[]struct{} is 5% faster in time and 10% less memory consumption comparing to map[]bool when it comes to a big Set.
Using map[T]struct{}
:
m := map[T]struct{}{}
if _, ok := m["key"]; ok {
// ...
}
Using map[T]bool
:
m := map[T]bool{}
if m["key"] {
// ...
}
Converting a string slice into a map[string]struct{}
:
s := []string{"a", "b", "c"}
m := ToMapOfEmptyStruct(s)
assert.Equal(t, map[string]struct{}{
"a": {},
"b": {},
"c": {},
}, m)
Converting a slice of structs into a map[string]bool
with a custom key function:
type outer struct {
s string
}
s := []outer{
{s: "a"},
{s: "b"},
{s: "c"},
}
m := ToMapOfBoolFunc(s, func (t outer) string { return t.s })
assert.Equal(t, map[string]bool{
"a": true,
"b": true,
"c": true,
}, m)
I wasn't able to find an existing library which provides this, yet I needed it for almost every project I worked on. So I wrote it myself.
See also:
- Standard library since Go 1.21 has
slices
andmaps
packages with generics, butslices
does not support converting slices to maps in any way, andmaps
only collects keys and values of maps to a slice. - https://github.com/spf13/cast has a number of ToStringMap functions, but they don't take slices as input, only support string keys, and they don't allow to specify a key function.
- test coverage
- benchmarks to compare
map[T]bool
withmap[T]struct{}