闭包

以前看js的时候,老是说,闭包闭包,但是一直搞不清楚,感觉就像个函数。最近看go,看到这篇文章,感觉有点明了。
Go by Example 中文:闭包
在我看来,闭包就是匿名函数使用了外部变量。

在wiki里的描述:
在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(function closures),是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。
在没有闭包的语言中,变量的生命周期只限于创建它的环境。但在有闭包的语言中,只要有一个闭包引用了这个变量,它就会一直存在。清理不被任何函数引用的变量的工作通常由垃圾回收完成

package main

import "fmt"

func intSeq() func() int {
   i := 0
   return func() int {
      i = i + 1
      return i
   }
}

func main() {
   nextInt := intSeq();
   fmt.Println(nextInt())
   fmt.Println(nextInt())
   fmt.Println(nextInt())
   fmt.Println(nextInt())
   fmt.Println(nextInt())

   fmt.Println("-------")
   nextInt2 := intSeq();
   fmt.Println(nextInt2())

   fmt.Println("-------")
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.