Find function for arrays/slices

How to write a functional Find function in golang using generics

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)
	}
}

Technologies: