golang 函数
发布时间:2020-12-16 19:00:18 所属栏目:大数据 来源:网络整理
导读:函数作为值、类型 在Go中函数也是一种变量,我们可以通过 type 来定义它,它的类型就是所有拥有相同的参数,相同的返回值的一种类型 type typeName func(input1 inputType1,input2 inputType2 [,...]) (result1 resultType1 [,...]) 函数作为类型到底有什么
函数作为值、类型 在Go中函数也是一种变量,我们可以通过 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) } 函数当做值和类型在我们写一些通用接口的时候非常有用,通过上面例子我们看到 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |