Find function for arrays/slices in Go

How to write a functional Find function in golang using generics, including a unit test. A taste of functional programming!


Find returns the first element in the input slice for which the predicate function returns true, along with a boolean indicating if such an element was found. The function f takes an element of type A and returns a boolean.

func Find[A any](input []A, f func(A) bool) (A, bool) {
	for _, v := range input {
		if f(v) {
			return v, true
		}
	}
	var defaultVal A
	return defaultVal, false
}

and this is a unittest for the function:

func TestFind(t *testing.T) {
	input := []int{1, 2, 3, 4, 5}
	f := func(a int) bool {
		return a == 3
	}
	expected := 3
	result, found := util.Find(input, f)
	if !found || result != expected {
		t.Errorf("Expected %v, got %v", expected, result)
	}
}

Linked Technologies

What it's made of

illustration of Go
Go

Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.