Search for an element and exit early when found:
nums := []int{1, 2, 3, 4, 5}
target := 3
found := false
for _, n := range nums {
if n == target {
found = true
break
}
}
Using break when you find the target avoids unnecessary iterations. This pattern returns as soon as possible instead of checking every element.