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

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.

主站蜘蛛池模板: 诸暨市| 班玛县| 鲁甸县| 饶平县| 武穴市| 额敏县| 疏附县| 呼伦贝尔市| 比如县| 武宣县| 额济纳旗| 延长县| 镇原县| 同仁县| 安国市| 库伦旗| 鄂伦春自治旗| 彩票| 昌江| 南宫市| 疏勒县| 大宁县| 蛟河市| 定西市| 承德县| 若尔盖县| 太原市| 侯马市| 福鼎市| 顺义区| 隆德县| 沙洋县| 阳信县| 民乐县| 惠安县| 德昌县| 广德县| 河曲县| 吉林省| 长顺县| 无为县|