Golang 函数变量

栏目: Go · 发布时间: 6年前

内容简介:在go中函数也是一种变量,可以通过type定义这种变量的类型。拥有相同参数和相同返回值的函数属于同一种类型。其优点是,既然是一种变量,我们就可以将函数作为值进行传递。下面的例子中可以看到,函数isOdd和isEven作为参数传递给函数filter,使得filter函数更灵活。

go 中函数也是一种变量,可以通过type定义这种变量的类型。拥有相同参数和相同返回值的函数属于同一种类型。

其优点是,既然是一种变量,我们就可以将函数作为值进行传递。

下面的例子中可以看到,函数isOdd和isEven作为参数传递给函数filter,使得filter函数更灵活。

type functionType 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 functionType) []int {
    var result []int
    for _, value := range slice {
        if f(value) {
            result = append(result, value)
        }
    }
    return result
}   
func test(){
    slice := []int {1, 2, 3, 4, 5, 7}
    fmt.Println("slice = ", slice)
    odd := filter(slice, isOdd)    // 函数当做值来传递了
    fmt.Println("Odd elements of slice are: ", odd)
    even := filter(slice, isEven)  // 函数当做值来传递了
    fmt.Println("Even elements of slice are: ", even)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Big Java Late Objects

Big Java Late Objects

Horstmann, Cay S. / 2012-2 / 896.00元

The introductory programming course is difficult. Many students fail to succeed or have trouble in the course because they don't understand the material and do not practice programming sufficiently. ......一起来看看 《Big Java Late Objects》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换