- Hands-On Full Stack Development with Go
- Mina Andrawos
- 214字
- 2021-07-02 12:33:30
Closures
A function can also be a closure. A closure is a function value that's bound to variables outside its body. This means that a closure can access and change values on those variables. It is hard to understand closures without an example. Here is another flavor of the adder function, which returns a closure:
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
The closure in the preceding example has access to the sum variable, which means that it will remember the current value of the sum variable, and will also be able to change the value of the sum variable. Again, this is best explained with another example:
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
// when we call "adder()",it returns the closure
sumClosure := adder() // the value of the sum variable is 0
sumClosure(1) //now the value of the sum variable is 0+1 = 1
sumClosure(2) //now the value of the sum variable is 1+2=3
//Use the value received from the closure somehow
}
We have covered the basics of Go. In the following section, we'll move on and discuss Go data structures.
推薦閱讀
- ASP.NET Web API:Build RESTful web applications and services on the .NET framework
- Learning Real-time Processing with Spark Streaming
- 區塊鏈架構與實現:Cosmos詳解
- Learning Linux Binary Analysis
- INSTANT Sencha Touch
- Python神經網絡項目實戰
- 零基礎學Python網絡爬蟲案例實戰全流程詳解(高級進階篇)
- 響應式架構:消息模式Actor實現與Scala、Akka應用集成
- Node Cookbook(Second Edition)
- Python深度學習原理、算法與案例
- Programming with CodeIgniterMVC
- Java7程序設計入門經典
- Julia High Performance(Second Edition)
- ASP.NET開發寶典
- C++17 By Example