What is the use of golang closure?

(*-*)浩
Release: 2019-12-27 14:16:55
Original
3672 people have browsed it

What is the use of golang closure?

What is a closure?

Go function can be a closure. A closure is a function value that references a variable outside the function body.(Recommended learning:go)

This function can access and assign values to the referenced variable; in other words, this function is "bound" to this variable superior.

My unreliable understanding is that a closure is equivalent to an instance of a class, and variables outside the function body are equivalent to the variables stored in this instance.

When there is no closure, the function is a one-time transaction. After the function is executed, the value of the variable in the function cannot be changed (the memory should be released);

With the closure The function becomes the value of a variable. As long as the variable is not released, the function will always be alive and exclusive, so the value of the variable in the function can be changed later (because this way the memory will not be reclaimed by Go, which will always cached there).

The main significance of closure

Reduce the scope of variables and reduce the pollution of global variables. If the following accumulation is implemented using global variables, the global variables will be easily contaminated by others.

At the same time, if I want to implement n accumulators, I need n global variables each time.

Using the backpack, each generated accumulator myAdder1, myAdder2 := adder(), adder() has its own independent sum, and sum can be regarded as myAdder1.sum and myAdder2.sum.

Use the backpack to implement functions with their own status!

package main import ( "fmt" ) func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } func main() { myAdder := adder() // 从1加到10 for i := 1; i <= 10; i++ { myAdder(i) } fmt.Println(myAdder(0)) // 再加上45 fmt.Println(myAdder(45)) }
Copy after login

Result:

55// 1+...+10 100
Copy after login

The above is the detailed content of What is the use of golang closure?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!