slices

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2026 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

Package slices provides generic slice utilities extending the standard slices package.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Filter

func Filter[T any](items []T, fn func(T) bool) []T

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

func FilterE[T any](items []T, fn func(T) (bool, error)) ([]T, error)

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

func MapE[T, U any](items []T, fn func(T) (U, error)) ([]U, error)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL