Closures in Go

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

闭包is a combination of a function and its associated reference environment (i.e., closure = function + reference environment). [1] In the program design, 对象 is attached to the behavior of data, and 闭包 is attached to the data of the behavior.
Let's take a look at the practical examples of closures in the Go language:

 Package MainImport"FMT"func Exfunc(N int)func(){  sum := n A: = func () {sum++ fmt.  Println (SUM) //Call a variable outside this function  }return a}func Main(){  myFunc := Exfunc (ten) myanotherfunc: = exfunc (myfun) C () //These two output one by one ,myFunc ()myanotherfunc ( )//The output of these two sentences,  A Myanotherfunc ()                   }

The anonymous function and the variable num in exfunc form a closure. Running this code will give you the following results:

11122122

Closures can be thought of as a class that executes in a function that alters its reference environment during execution. For example main , in a function, we create two separate closures, and the process of two closures changes the respective referencing environment.
If you want to know the closure of the system, you can view the references [3]

Reference:
1. The closed-loop discussion on function programming (Closure)
2. Closures in Go
3. Concept, form and application of closures

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.