Does Go allow a function to use another function as a parameter? -
the problem happening @ line 17 in go code. below program in python , go can see i'm attempting do. python works, go attempts have failed. read golang.org back, , google turned nothing, well.
def my_filter(x): if x % 5 == 0: return true return false #function returns list of numbers satisfy filter def my_finc(z, my_filter): = [] x in z: if my_filter(x) == true: a.append(x) return print(my_finc([10, 4, 5, 17, 25, 57, 335], my_filter))
now, go version i'm having troubles with:
package main import "fmt" func filter(a []int) bool { var z bool := 0; < len(a); i++ { if a[i]%5 == 0 { z = true } else { z = false } } return z } func finc(b []int, filter) []int { var c []int := 0; < len(c); i++ { if filter(b) == true { c = append(c, b[i]) } } return c } func main() { fmt.println(finc([]int{1, 10, 2, 5, 36, 25, 123}, filter)) }
yes, go can have functions 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 _, := 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 need type pass in.
type filter func(int) bool
i cleaned bit of code make more idiomatic. replaced loops range clauses.
for := 0; < len(b); i++ { if filter(b[i]) == true { c = append(c, b[i]) } }
becomes
for _, := range b { if filter(i) { c = append(c, i) } }
Comments
Post a Comment