头等函数一

package main

import (  
    "fmt"
)

// 头等函数
// 支持头等函数(First Class Function)的编程语言,可以把函数赋值给变量,也可以把函数作为其它函数的参数或者返回值。Go 语言支持头等函数的机制

/* 
1、匿名函数(特例,闭包:当一个匿名函数所访问的变量定义在函数体的外部时,就称这样的匿名函数为闭包)
2、自定义函数类型
3、高阶函数(接收一个或多个函数作为参数,返回值是一个函数)
*/

// 自定义了一个函数类型
type add func(a int, b int) int

// 参数为匿名函数
func simple(a func(a, b int) int) {  
    fmt.Println(a(60, 7))
}

// 返回值为匿名函数
func simple2() func(a, b int) int {  
    f := func(a, b int) int {
        return a + b
    }
    return f
}

// 闭包
func appendStr() func(string) string {  
    t := "Hello"
    c := func(b string) string {
        t = t + " " + b
        return t
    }
    return c
}


func main() {  
    // 方式一
    a := func() {
        fmt.Println("hello world first class function")
    }
    a()
    fmt.Printf("%T", a)

    // 方式二
    func() {
        fmt.Println("hello world first class function")
    }()

    // 方式三,可以带参数
    func(n string) {
        fmt.Println("Welcome", n)
    }("Gophers")

    var b add = func(a int, b int) int {
        return a + b
    }
    s := b(5, 6)
    fmt.Println("Sum", s)

    // 把函数作为参数,传递给其它函数
    // f为一个匿名函数,作为simple函数的参数
    f := func(a, b int) int {
        return a + b
    }
    simple(f)

    // 在其它函数中返回函数
    s2 := simple2()
    fmt.Println(s2(60, 7))

    // 闭包
    a2 := appendStr()
    b2 := appendStr()
    fmt.Println(a2("World"))
    fmt.Println(b2("Everyone"))

    fmt.Println(a2("Gopher"))
    fmt.Println(b2("!"))
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容