您的位置:首页 > 编程语言 > Go语言

golang 函数作为类型

2015-04-15 16:25 225 查看
golang 函数作为类型

package main

import "fmt"

type A func(int, int)

func (f A)Serve() {
fmt.Println("serve2")
}

func serve(int,int) {
fmt.Println("serve1")
}

func main() {
a := A(serve)
a(1,2)
a.Serve()
}


type functinTyoe 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 functinTyoe) []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)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: