Yes, Go can have functions as parameters:
package main
import "fmt"
func myFilter(a int) bool {
return a%5 == 0
}
type Filter func(int) bool
func finc(b []int, filter Filter) []int {
var c []int
for _, i := range b {
if filter(i) {
c = append(c, i)
}
}
return c
}
func main() {
fmt.Println(finc([]int{1, 10, 2, 5, 36, 25, 123}, myFilter))
}
The key is you need the type to be passed.
type Filter func(int) bool
I also cleared some code to make it more idiomatic. I replaced your cycles with range suggestions.
for i := 0; i < len(b); i++ {
if filter(b[i]) == true {
c = append(c, b[i])
}
}
becomes
for _, i := range b {
if filter(i) {
c = append(c, i)
}
}
source
share