Filter a slice
suggest changeGo has no built-in filter operation for slices, so filter with a loop:
- create a new slice for the result
- iterate over all elements of original slice
- check if element should be retained or rejected
- if should be retained, append to result
func filterEvenValues(a []int) []int {
var res []int
for _, el := range a {
if el%2 == 0 {
continue
}
res = append(res, el)
}
return res
}
a := []int{1, 2, 3, 4}
res := filterEvenValues(a)
fmt.Printf("%#v\n", res)
[]int{1, 3}
We can do it more efficiently by reusing underlying array of the slice because we know that the result will always be smaller than original slice:
func filterEvenValuesInPlace(a []int) []int {
// create a zero-length slice with the same underlying array
res := a[:0]
for _, v := range a {
if v%2 == 0 {
continue
}
// keep the same values as filterEvenValues: drop evens
res = append(res, v)
}
return res
}
func main() {
a := []int{1, 2, 3, 4}
res := filterEvenValuesInPlace(a)
fmt.Printf("%#v\n", res)
}
[]int{1, 3}
This avoids allocating a new array for the result. It is also more dangerous.
res uses the same backing array as a, and append overwrites that array. After the call, a no longer has its original elements, which is not obvious at the call site. The result is never longer than the input, which is why writing into a[:0] does not overwrite an element before it is read.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents