How to Filter a Slice in Go

Filter a Go slice using slices.DeleteFunc to remove items in place or slices.Filter to create a new slice with matching elements.

Use slices.DeleteFunc to filter a slice in Go by removing elements that match a condition. This function modifies the slice in place and returns the new length.

import "slices"

nums := []int{1, 2, 3, 4, 5}
nums = slices.DeleteFunc(nums, func(n int) bool {
    return n%2 == 0 // Remove even numbers
})
// nums is now [1, 3, 5]

For an alternative approach, use a loop to build a new slice:

nums := []int{1, 2, 3, 4, 5}
var filtered []int
for _, n := range nums {
    if n%2 != 0 {
        filtered = append(filtered, n)
    }
}
// filtered is [1, 3, 5]