Documentation
¶
Overview ¶
Package slices provides generic slice utilities extending the standard slices package.
Index ¶
- func Filter[T any](items []T, fn func(T) bool) []T
- func FilterE[T any](items []T, fn func(T) (bool, error)) ([]T, error)
- func GroupBy[T any, K comparable](items []T, keyFn func(T) K) map[K][]T
- func Map[T, U any](items []T, fn func(T) U) []U
- func MapE[T, U any](items []T, fn func(T) (U, error)) ([]U, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Filter ¶
Filter returns elements where fn returns true.
Example ¶
package main
import (
"fmt"
"github.com/foomo/go/slices"
)
func main() {
result := slices.Filter([]int{1, 2, 3, 4, 5}, func(n int) bool {
return n%2 == 0
})
fmt.Println(result)
}
Output: [2 4]
func FilterE ¶ added in v0.6.0
FilterE returns elements where fn returns true
Example ¶
package main
import (
"fmt"
"github.com/foomo/go/slices"
)
func main() {
result, _ := slices.FilterE([]int{1, 2, 3, 4, 5}, func(n int) (bool, error) {
return n%2 == 0, nil
})
fmt.Println(result)
}
Output: [2 4]
func GroupBy ¶
func GroupBy[T any, K comparable](items []T, keyFn func(T) K) map[K][]T
GroupBy groups elements by key.
Example ¶
package main
import (
"fmt"
"github.com/foomo/go/slices"
)
func main() {
type item struct {
name string
category string
}
items := []item{
{"apple", "fruit"},
{"carrot", "vegetable"},
{"banana", "fruit"},
}
groups := slices.GroupBy(items, func(i item) string {
return i.category
})
fmt.Println(len(groups))
fmt.Println(len(groups["fruit"]))
fmt.Println(len(groups["vegetable"]))
}
Output: 2 2 1
func Map ¶
func Map[T, U any](items []T, fn func(T) U) []U
Map transforms each element using fn.
Example ¶
package main
import (
"fmt"
"github.com/foomo/go/slices"
)
func main() {
result := slices.Map([]int{1, 2, 3}, func(n int) int {
return n * 2
})
fmt.Println(result)
}
Output: [2 4 6]
func MapE ¶ added in v0.6.0
MapE transforms each element using fn and returns an error if any.
Example ¶
package main
import (
"fmt"
"github.com/foomo/go/slices"
)
func main() {
result, _ := slices.MapE([]int{1, 2, 3}, func(n int) (int, error) {
return n * 2, nil
})
fmt.Println(result)
}
Output: [2 4 6]
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.