首页 > 其他 > 详细

golang 函数作为类型

时间:2015-04-15 18:28:15      阅读:170      评论:0      收藏:0      [点我收藏+]
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)
}
 

 

golang 函数作为类型

原文:http://www.cnblogs.com/rojas/p/4428961.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!