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

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.

主站蜘蛛池模板: 金堂县| 高台县| 游戏| 天水市| 上思县| 镇康县| 澄江县| 女性| 石楼县| 翁源县| 平安县| 股票| 张家港市| 思茅市| 台湾省| 静乐县| 同江市| 宁海县| 交城县| 温泉县| 福州市| 邵武市| 河西区| 巴林左旗| 沧源| 建水县| 民县| 确山县| 福建省| 襄垣县| 中宁县| 武宣县| 乌兰察布市| 嘉祥县| 恭城| 嘉祥县| 西丰县| 伊吾县| 广昌县| 安龙县| 河西区|