简单理解golang中的闭包(转载)

何为闭包


关于闭包的概念,有些抽象。 
WIKI: 
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions.

A closure is a function value that references variables from outside its body. 


个人理解: 
闭包就是能够读取其他函数内部变量的函数。 
只有函数内部的子函数才能读取局部变量,因此可以把闭包简单理解成”定义在一个函数内部的函数”。

golang中使用闭包

返回闭包
 

package main

import "fmt"

func outer(name string) func() {
    // variable
    text := "Modified " + name

    // closure. function has access to text even after exiting this block
    foo := func() {
        fmt.Println(text)
    }

    // return the closure
    return foo
}

func main() {
    // foo is a closure
    foo := outer("hello")

    // calling a closure
    foo()
}

陷阱:

 

斐波拉切数列

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    x, y := 0, 1
    return func() int {
        x, y = y, x+y
        return x
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

 

发布了4 篇原创文章 · 获赞 0 · 访问量 188

猜你喜欢

转载自blog.csdn.net/cyb_17302190874/article/details/105689664
今日推荐