Solution Review: Filtering with Higher-Order Functions
This lesson discusses the solution to the challenge given in the previous lesson.
package mainimport ("fmt")func main() {s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}s = Filter(s, even)fmt.Println(s)}// Filter returns a new slice holding only// the elements of s that satisfy fn()func Filter(s []int, fn func(int) bool) []int {var p []int // == nilfor _, i := range s {if fn(i) {p = append(p, i)}}return p}func even(n int) bool {if n%2 == 0 {return true}return false}
Get hands-on with 1400+ tech skills courses.