go语言中将函数作为变量传递

在Go中函数也是一种变量,我们可以通过type来定义它,它的类型就是所有拥有相同的参数,相同的返回值的一种类型,函数当做值和类型在我们写一些通用接口的时候非常有用,通过下面这个例子我们可以看到testInt类型是一个函数类型,然后两个filter函数的参数和返回值与testInt类型一样的,但是我们可以实现很多种逻辑,这样使得我们的程序可以变得非常的灵活。

package main

import (
        "fmt"
)

//声明了一个函数类型
type testInt func(int) bool

func isOdd(integer int) bool {
        if integer%2 == 0 {
                return false
        }
        return true
}

func isEven(integer int) bool {
        if integer%2 == 0 {
                return true
        }
        return false
}

//声明的函数在这个地方当做了一个参数
func filter(slice []int, f testInt) []int {
        var result []int
        for _, value := range slice {
                if f(value) {
                        result = append(result, value)
                }
        }
        return result
}
func main() {
        slice := []int{1, 2, 3, 4, 5, 7}
        fmt.Println("slice = ", slice)
        //将函数当做值来传递
        odd := filter(slice, isOdd)
        fmt.Println("奇数是:", odd)
        //将函数当做值来传递
        even := filter(slice, isEven)
        fmt.Println("偶数是:", even)
}

//运行结果
$ go run test.go
slice =  [1 2 3 4 5 7]
奇数是: [1 3 5 7]
偶数是: [2 4]