slices

package
v0.17.1 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 0 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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