- 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.
推薦閱讀
- scikit-learn Cookbook
- C及C++程序設計(第4版)
- Web程序設計及應用
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- R語言數據可視化之美:專業圖表繪制指南
- WSO2 Developer’s Guide
- Linux命令行與shell腳本編程大全(第4版)
- Learning Unity 2D Game Development by Example
- Hands-On Full Stack Development with Spring Boot 2.0 and React
- Deep Learning with R Cookbook
- C#面向對象程序設計(第2版)
- Visual C#(學習筆記)
- Python人工智能項目實戰
- Learning PrimeFaces Extensions Development
- 三步學Python