内容简介:在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)
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 【项目实用】Css 变量及函数
- 015.Python函数名的使用以及函数变量的操作
- Shell编程—【04】函数的定义、参数、变量作用域、函数库
- JS变量声明和函数声明提升
- golang学习笔记(一):包,变量,函数
- 如何使用 Linux 内核中没有被导出的变量或函数?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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》 这本书的介绍吧!