Filter a slice

suggest change

Go doesn't have a generic functionality for filtering slices so we have to do it the old-fashioned way:

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 re-using 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 {
			// collect only wanted values
			res = append(res, v)
		}
	}
	return res
}

func main() {
	a := []int{1, 2, 3, 4}
	res := filterEvenValuesInPlace(a)
	fmt.Printf("%#v\n", res)
}
[]int{2, 4}

This avoids allocating a new array for the result. It's also more dangerous.

The original slice a is now modified but it's not obvious from looking at the code.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents