Golang 函数变量

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

内容简介:在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)
}

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

查看所有标签

猜你喜欢:

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

Introduction to Computer Science Using Python

Introduction to Computer Science Using Python

Dierbach, Charles / 2012-12 / $ 133.62

Introduction to Computer Science Using Python: A Computational Problem-Solving Focus introduces students to programming and computational problem-solving via a back-to-basics, step-by-step, objects-la......一起来看看 《Introduction to Computer Science Using Python》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

随机密码生成器
随机密码生成器

多种字符组合密码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具