slices

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 0 Imported by: 0

Documentation

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 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]

Types

This section is empty.

Jump to

Keyboard shortcuts

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