【问题标题】:Does Go allow a function to use another function as a parameter?Go 是否允许一个函数使用另一个函数作为参数?
【发布时间】:2014-02-06 04:56:15
【问题描述】:

问题发生在 Go 代码的第 17 行。下面是 python 和 Go 中的程序,所以你可以确切地看到我正在尝试做的事情。 Python 工作,我的 Go 尝试都失败了。已经背靠背阅读了 golang.org,而 google 也没有发现任何东西。

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))

现在,我遇到问题的 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))
}

【问题讨论】:

    标签: function parameters go nested arguments


    【解决方案1】:

    是的,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))
    }
    

    关键是你需要一个类型来传入。

    type Filter func(int) bool
    

    我还清理了一些代码,使其更加地道。我用范围子句替换了你的 for 循环。

    for i := 0; i < len(b); i++ {
        if filter(b[i]) == true {
            c = append(c, b[i])
        }
    }
    

    变成

    for _, i := range b {
        if filter(i) {
            c = append(c, i)
        }
    }
    

    【讨论】:

    • 不错的答案。作为评论,type Filter 不是强制性的(但推荐),而不是写func finc(b []int, filter Filter) []int { 他们可以使用func finc(b []int, filter func(int)bool) []int {
    猜你喜欢
    • 2018-11-13
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2013-07-10
    • 2015-12-24
    相关资源
    最近更新 更多