kcm*_*ard 4 parameters arguments nested function go
问题发生在Go代码的第17行.下面是python和Go中的程序,所以你可以看到我正在尝试做什么.Python工作,我的Go尝试都失败了.已经连续阅读了golang.org,谷歌也没有看到任何内容.
def my_filter(x):
if x % 5 == 0:
return True
return False
#Function which returns a list of those numbers which satisfy the filter
def my_finc(Z, my_filter):
a = []
for x in Z:
if my_filter(x) == True:
a.append(x)
return a
print(my_finc([10, 4, 5, 17, 25, 57, 335], my_filter))
Run Code Online (Sandbox Code Playgroud)
现在,Go版本我遇到了麻烦:
package main
import "fmt"
func Filter(a []int) bool {
var z bool
for i := 0; i < len(a); i++ {
if a[i]%5 == 0 {
z = true
} else {
z = false
}
}
return z
}
func finc(b []int, Filter) []int {
var c []int
for i := 0; i < 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))
}
Run Code Online (Sandbox Code Playgroud)
是的,Go可以将函数作为参数:
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))
}
Run Code Online (Sandbox Code Playgroud)
关键是你需要传递一种类型.
type Filter func(int) bool
Run Code Online (Sandbox Code Playgroud)
我还清理了一些代码,使其更具惯用性.我用范围子句替换了你的for循环.
for i := 0; i < len(b); i++ {
if filter(b[i]) == true {
c = append(c, b[i])
}
}
Run Code Online (Sandbox Code Playgroud)
变
for _, i := range b {
if filter(i) {
c = append(c, i)
}
}
Run Code Online (Sandbox Code Playgroud)