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

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.

主站蜘蛛池模板: 确山县| 梁平县| 射阳县| 永顺县| 南通市| 澎湖县| 县级市| 灵宝市| 东丰县| 东光县| 双峰县| 永济市| 开化县| 崇左市| 前郭尔| 固镇县| 镇雄县| 仁怀市| 集贤县| 朝阳县| 淮南市| 都昌县| 余庆县| 忻城县| 财经| 晋江市| 武威市| 察雅县| 唐山市| 赣榆县| 安陆市| 荣昌县| 景德镇市| 杨浦区| 灵川县| 齐河县| 林周县| 麻江县| 嘉禾县| 双柏县| 探索|