Essential Go Slices  Suggest an edit

Filter a slice

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

// TODO: link filter_slice_simple.go

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:

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 but is also more dangerous. The original slice is now modified but we might use it as

  ↑ ↓ to navigate     ↵ to select     Esc to close