- 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.
推薦閱讀
- Extending Jenkins
- Arduino開發實戰指南:LabVIEW卷
- 編寫整潔的Python代碼(第2版)
- PHP+MySQL網站開發技術項目式教程(第2版)
- TestNG Beginner's Guide
- Learning Python Design Patterns(Second Edition)
- Visual Basic程序設計習題解答與上機指導
- MySQL數據庫管理與開發實踐教程 (清華電腦學堂)
- 深入淺出PostgreSQL
- 前端HTML+CSS修煉之道(視頻同步+直播)
- Windows Phone 7.5:Building Location-aware Applications
- Julia 1.0 Programming Complete Reference Guide
- Spring 5 Design Patterns
- HTML5+CSS3+JavaScript 從入門到項目實踐(超值版)
- 深入實踐DDD:以DSL驅動復雜軟件開發