Go language closures How to capture parameters

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

See Code:

 PackageMainImport("FMT")funcMain()  {varWhatever [5]struct{} forI: =RangeWhatever {fmt.Println(i)}//part 1        forI: =RangeWhatever {defer func() {FMT.Println(i)} ()       }//part 2        forI: =RangeWhatever {defer func(nint) {FMT.Println(n)} (i)}//part 3}
Part 1 does not have to explain what, at a glance, is typical of a go language closure, which captures the variable "I", for the part 2, note that the "reference" is holding the "references" not a copy yo!  So when Part2 's for loop ends, the value of the variable "i" is exactly 4, so the output of the closure is 4. For Part 3, although it is also a closure, but does not capture the variable "I", but instead of the normal way to call the closure, and for the form: defer f (e) of the statement, the F function or closure is not immediately executed, but its parameter expression will be evaluated immediately, is evaluated, such as: F (0), F ( 1) ... f (4); and since the defer call is executed in a state-of-the-art manner, the output of the PART3 is: 4,3,2,1,0; so part2 is executed after part3, so the output is reversed!


Original: Http://stackoverflow.com/questions/16010694/how-golangs-defer-capture-closures-parameter


Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com

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.