go语言中函数作为值、类型
2017-09-15 11:44
337 查看
函数作为值、类型
在Go中函数也是一种变量,我们可以通过type来定义它,它的类型就是所有拥有相同的参数,相同的返回值的一种类型
type typeName func(input1 inputType1 , input2 inputType2 [, ...]) (result1 resultType1 [, ...])
函数作为类型到底有什么好处呢?那就是可以把这个类型的函数当做值来传递,请看下面的例子
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 elements of slice are: ", odd) even := filter(slice, isEven) // 函数当做值来传递了 fmt.Println("Even elements of slice are: ", even) }
函数当做值和类型在我们写一些通用接口的时候非常有用,通过上面例子我们看到
testInt这个类型是一个函数类型,然后两个
filter函数的参数和返回值与
testInt类型是一样的,但是我们可以实现很多种的逻辑,这样使得我们的程序变得非常的灵活。
参考:https://github.com/Agzs/golang-ebook/blob/master/zh/02.3.md
相关文章推荐
- go语言将函数作为参数传递
- 【Go入门教程5】流程(if、goto、for、switch)和函数(多个返回值、变参、传值与传指针、defer、函数作为值/类型、Panic和Recover、main函数和init函数、import)
- go语言笔记——是c开发的 lex yacc进行词法和语法分析,go不支持函数和运算符重载,不支持类型继承,也不支持断言,还有泛型
- 简单了解Go语言中函数作为值以及函数闭包的使用
- C语言简单宏函数实现C++模板功能(类型本身作为函数参数)
- go语言将函数作为参数传递
- 56.笔记go语言——go的函数类型
- go语言函数作为参数传递
- go语言中将函数作为变量传递
- go语言 各数据类型传值函数改变是否影响原值
- GO语言函数与类型
- GO语言学习-复杂类型(1)
- GO语言学习-复杂类型(2)
- 你猜对了么?一个函数考察Go 语言闭包、defer的用法
- go语言学习-golang的基本数据类型
- C语言数组作为函数参数
- golang 函数作为类型
- 详解 Go 语言中 Map 类型和 Slice 类型的传递
- T-SQL: 17 个与日期时间相关的自定义函数(UDF),周日作为周的最后一天,均不受 @@DateFirst、语言版本影响
- Go 语言方法接受者类型的选择