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]