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

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.

主站蜘蛛池模板: 秀山| 荔浦县| 北安市| 沙河市| 许昌市| 武宁县| 罗山县| 沅陵县| 兴隆县| 彭州市| 阿拉善右旗| 奇台县| 元阳县| 安化县| 内黄县| 台南县| 县级市| 宁南县| 封开县| 清远市| 铜川市| 麻阳| 报价| 鞍山市| 玉环县| 儋州市| 静宁县| 屯留县| 牡丹江市| 隆化县| 定南县| 合川市| 大丰市| 沛县| 洮南市| 江山市| 水富县| 东安县| 图们市| 五台县| 鹤庆县|