Go语言允许一个函数将另一个函数作为参数使用吗?

huangapple go评论100阅读模式
英文:

Does Go allow a function to use another function as a parameter?

问题

问题发生在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))

现在是我在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))
}
英文:

The problem is happening at line 17 in the Go code. Below is the program in python and Go so you can see exactly what I'm attempting to do. Python works, my Go attempts have all failed. Already read golang.org back to back, and google turned up nothing, as well.

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

Now, the Go version which I'm having troubles with:

package main

import &quot;fmt&quot;

func Filter(a []int) bool {
	var z bool
	for i := 0; i &lt; 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 &lt; 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))
}

答案1

得分: 8

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

我还对代码进行了一些清理,使其更符合惯用写法。我用range循环替换了你的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)
    }
}
英文:

Yes, Go can have functions as parameters:

package main

import &quot;fmt&quot;

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 a type to pass in.

type Filter func(int) bool

I also cleaned up a bit of the code to make it more idiomatic. I replaced your for loops with range clauses.

for i := 0; i &lt; 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)
    }
}

huangapple
  • 本文由 发表于 2014年2月6日 12:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/21594333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定