30. Toad Notes Go language-about closures

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

30. Toad Notes Go language-about closures

The anonymous function of Go is a closed packet.

Concept

Closures are blocks of code that can contain free (unbound object-specific) variables that are not defined within the code block or in any global context, but are defined in the context in which the code block is defined. The code block to execute (because free variables are included in the code block, so these free variables and the objects they refer to are not freed) provide a binding computing environment (scope) for free variables.

The value of closures

The value of a closure is that it can be used as a function object or as an anonymous function, which means, for a type system, not only to represent the data but also to represent the code. Most languages that support closures use functions as first-level objects, meaning that these functions can be stored in variables as arguments to other functions, and most importantly, they can be dynamically created and returned by a function.

Closures in the Go language also refer to variables outside the function. The closure implementation ensures that as long as the closure is used, the variables referenced by the closure will persist.

Code

Package Main

Import (

"FMT"

)

Func Main () {

var jint = 5

A: =func () func () {

vari int = 10

Returnfunc () {

Fmt. Printf ("I,j:%d,%d\n", I, J)

}

}()

A ()

J *= 2

A ()

}

Perform

I,j:10, 5

I,j:10, 10

In the above example, the closure function that the variable a points to refers to the values of the local variables I and j,i are isolated, cannot be modified outside the closure, changes the value of J, and then calls a again, discovering that the result is a modified value.

In the closure function that the variable a points to, only the internal anonymous function can access the variable I and cannot be accessed by other means, thus guaranteeing the security of I.

Related Article

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.