IndexOf function for arrays/slices in Go
How to write a functional IndexOf function in Go using generics. Surprisingly helpful during mundane tasks!
IndexOf returns the index of the first occurrence of the specified value in the input slice, or -1 if the slice does not contain the value.
func IndexOf[A comparable](input []A, value A) int {
for i, v := range input {
if v == value {
return i
}
}
return -1
}
and this is a unittest for the function:
func TestIndexOf(t *testing.T) {
input := []int{1, 2, 3, 4, 5}
value := 3
expected := 2
result := util.IndexOf(input, value)
if expected != result {
t.Errorf("Expected %v, got %v", expected, result)
}
}
Linked Technologies
What it's made of
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
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.