Closures in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

What closures are, closures are entities that are composed of functions and their associated reference environments (that is, closures = functions + reference environments).

This section can be see: http://www.cnblogs.com/ghj1976/archive/2013/02/08/2909364.html

The closure contains the external environment variable value, but the value of the environment variable is not the same as the anonymous function as the parameter copy, but the actual reference (or pointer, anyway a meaning), when the external variables change, the value of the closure can be used naturally change.

According to this principle, it is clear why several of the closure scenarios listed below are calculated as the corresponding values.

The following example is from: http://blog.csdn.net/liugao15/article/details/8296064

 
  

Example 1

Main
Import "FMT"
Main () {
fn [ten]func () 
i:= 0;i<len(FN); i++{ 
 fn[i]=func() {
 FMT. Println (i)
        }
    }
  for _,f:=rangefn{
 F ()
    }
}
Output value:

10
10
10
10
10
10
10
10
10
10
Exit code 0, process exited normally.

Principle: When executing f (), I uses a pointer to the I previously defined, and since the loop has already been completed, it all shows 10.

Example 2

 
  Main
"FMT"
Main () {
fn [ten]func(int) 
i:= 0;i<len(FN); i++{ 
 FN[I]=MAKE_FN ()
    }
This IDEpointer is used in i,f:=//closures 
 F (i)
    }
}
func int) {
func int) {  
 FMT. Println (i)
    }
}
Output:

0
1
2
3
4
5
6
7
8
9
Exit code 0, process exited normally.

The following example is from: http://lelouchhe.github.com/one_thing_about_closure_in_go/

Example 3

 
  Main
Import (
  "FMT"
  "Time"
)
Main () {
i:= 0;i<; i++{ 
func () {  
 FMT. Println (i)
        }()
    }
 time. Sleep (1e9)
}

This output is all 100, because this loop is running faster than Goroutine, Goroutine has not started, the for loop is over, and the value of I is 100, so I naturally within the closure is 100.

 
  

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.