go函数类型讲解

package main


import "fmt"


type functiontype func(int) bool  //声明一个函数类型


func isodd (integer int) bool {//判断一个整数是否是奇数
if integer % 2 != 0 {
return true
}
return false
}


func iseven(integer int) bool {//判断一个整数是否是偶数
if integer % 2 == 0 {
return true
}
return false
}


func filter(slice []int,f functiontype) []int {
var res []int
for _,value := range slice {
if f(value) {
res=append(res,value)
}
}
return res
}


func main() {
var slice = []int{1,2,3,4,5,6,7,8,9,10}
odd := filter(slice,isodd)//函数名当作值来传递
even := filter(slice,iseven)//函数名当作值来传递
fmt.Println("Odd elements of slice are:",odd)
fmt.Println("Even elements of slice are:",even)

}


运行:

E:\project\go\proj\src>go run functiontype.go
Odd elements of slice are: [1 3 5 7 9]
Even elements of slice are: [2 4 6 8 10]

你可能感兴趣的:(go)