官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 新安县| 汉源县| 广水市| 台南县| 松滋市| 定日县| 晋城| 太仓市| 福鼎市| 思茅市| 扎囊县| 伊吾县| 凤城市| 沁阳市| 忻城县| 德钦县| 右玉县| 固原市| 金昌市| 韩城市| 犍为县| 九寨沟县| 噶尔县| 凤台县| 缙云县| 宜州市| 胶州市| 沁水县| 仁寿县| 闵行区| 冀州市| 尤溪县| 太白县| 嘉兴市| 漠河县| 吴桥县| 邳州市| 冷水江市| 佛教| 余干县| 双城市|