Things to pay attention to when using closures and coroutines

Source: Internet
Author: User

Closures are a small technique that allows you to program in a very comfortable way. Go also supports closures. If you have never touched a closure, it is very difficult to understand what it is at the beginning, just like recursion, until you have actually written and used it, so that you can have a more specific understanding of it.


A closure is a function that contains the context environment required to run it. This environment may be several variables or may be others (usually variables ). The closure is a function that is incorrect. More specifically,A closure is a runtime environment that packages the external context environment of its scope.. It doesn't matter if you haven't understood the meaning of this closure for a while. This is a step-by-step process.


Let's look at an example of the most common online closure explanation:

Package mainimport "FMT" func A () func () int {value: = 0 return func () int {value ++ return value} // () at this point, the local variable value} func main () {B: = a () FMT should have been destroyed. println (B () FMT. println (B () FMT. println (B ())}

The running result is:

123

Let's take a good look at this code. We define a function a (). In a, we define another function B (), and B will return it to us as the return value. The role of B is to increase the value of A's local variable by 1 each call. However, after function a runs, it is reasonable to say that the value of the local variable has been destroyed, and B cannot operate on it. However, from the running result, the value is still "alive ". Yes, this is the so-called function that packs the Context Environment. B is a closure function, which not only defines its own operation flow, but also includes its value variable in Environment A above.

In this example, you may not see the function of the closure, but in fact, the closure is more or less required that the programming language support anonymous functions and the function is the first type in the Chinese language (you can assign a function to a variable and use the function as a parameter and return value ). I am not very familiar with the function of closures. Using closures in languages with many defects such as JS can bring the benefits of protecting variable access permissions and better modularity. For go, I think the biggest benefit of closures is:

1. You don't need to name a function ~

2. A temporary function can be defined in the nearest place.

3. you can directly use go func (){...} () in this way, you do not need to pre-define every function to be concurrent outside the current runtime environment.


After finishing the basic content of the closure, let's talk about the issues that should be paid attention to when using the closure. In principle, the biggest advantage of using a closure isConvenientBut do not always think of using closures in any case, because if you do not know about closures, the code you write may have unexpected running effects. Let's take a look at the following example:

Package mainimport ("FMT") func main () {done: = make (Chan bool, 3) For I: = 0; I <3; I ++ {go func () {// There is a problem here. Each routine packages the variable ifmt in the outer running environment. println (I) done <-true} ()} For I: = 0; I <3; I ++ {<-done }}

The running result is:

333

If you look at the code carefully, you should feel that the Code does not seem to have any problems. But what is the result of 1 2 3 ??? In fact, the go official guide also provides related examples for developers to pay attention to this issue when using closures and goroutine.

In this example, the three goroutines In the first loop do not run immediately after they are created,Because they are bound to the variable I in the outer runtime environment, because the outer runtime environment changes the I value at any time, the three routine cannot start to run because the loop ends..


The solution is to pass the outer context to the closure function as a parameter, as shown in the following code:

Package mainimport ("FMT") func main () {done: = make (Chan bool, 3) For I: = 0; I <3; I ++ {go func (index INT) {// pass I in the outer environment as a parameter to FMT. println (INDEX) done <-true} (I) // pass I in} For I: = 0; I <3; I ++ {<-done }}

In this case, the closure function does not need to bind the variable I in the outer environment. This issue must be noted because the goroutine and closure are often used together in go. If context packaging is not properly handled, unexpected running results may occur.



If reproduced, please indicate the source: http://blog.csdn.net/gophers




Things to pay attention to when using closures and coroutines

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.