📜  Golang 关闭

📅  最后修改于: 2021-10-24 14:11:42             🧑  作者: Mango

Go 语言提供了一个称为匿名函数的特殊函数。匿名函数可以形成闭包。闭包是一种特殊类型的匿名函数,它引用在函数本身之外声明的变量。它类似于访问在函数声明之前可用的全局变量。

例子:

// Golang program to illustrate how
// to create a Closure
package main
  
import "fmt"
  
func main() {
      
    // Declaring the variable
    GFG := 0
  
    // Assigning an anonymous  
    // function to a variable 
    counter := func() int {
       GFG += 1
       return GFG
    }
  
    fmt.Println(counter())
    fmt.Println(counter())
      
    
}

输出:

1
2

解释:变量GFG没有作为参数传递给匿名函数,但函数可以访问它。在这个例子中,有一个小问题,因为将在 main 中定义的任何其他函数都可以访问全局变量GFG并且它可以在不调用counter 函数 的情况下更改它。因此,闭包还提供了另一个方面,即数据隔离

// Golang program to illustrate how
// to create data isolation
package main
  
import "fmt"
  
// newCounter function to 
// isolate global variable
func newCounter() func() int {
    GFG := 0
    return func() int {
      GFG += 1
      return GFG
  }
}
func main() {
    // newCounter function is
    // assigned to a variable
    counter := newCounter()
  
    // invoke counter
    fmt.Println(counter())
    // invoke counter
    fmt.Println(counter())
      
    
}

输出:

1
2

说明:即使在newCounter()函数完成运行但newCounter()函数之外的其他代码都无法访问此变量后,闭包仍会引用变量GFG 。这就是在函数调用之间维护数据持久性同时还将数据与其他代码隔离的方式。