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

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.

主站蜘蛛池模板: 特克斯县| 泽州县| 武鸣县| 双桥区| 化州市| 蓬安县| 克什克腾旗| 平定县| 璧山县| 新竹县| 嘉祥县| 雅安市| 大港区| 淮南市| 长沙县| 腾冲县| 威宁| 卫辉市| 洛扎县| 石河子市| 正安县| 迁安市| 深泽县| 望都县| 民勤县| 永吉县| 黄浦区| 扎赉特旗| 章丘市| 巢湖市| 唐海县| 元谋县| 乳山市| 甘孜| 珠海市| 白沙| 南川市| 扎赉特旗| 谢通门县| 宝丰县| 彰武县|