Search⌘ K
AI Features

Solution Review: Filtering with Higher-Order Functions

Explore how to apply higher-order functions to filter slices in Go. Learn how to pass functions as parameters, process integer slices, and return filtered results, enhancing your skills in array and slice manipulation.

We'll cover the following...
Go (1.6.2)
package main
import (
"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 // == nil
for _, 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
}

The program above ...