zoukankan      html  css  js  c++  java
  • golang 函数作为类型

    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)
    }
     
  • 相关阅读:
    全面理解面向对象的 JavaScript
    账号
    移动端 前端框架 amaze ui
    javascript 精典案例分析一览
    前端事件系统(一)
    周总结12
    周总结11
    相比较于其他的同类软件
    团队冲刺第十五天
    团队冲刺第十四天
  • 原文地址:https://www.cnblogs.com/rojas/p/4428961.html
Copyright © 2011-2022 走看看