57. Toad Notes Go language--closures

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

57. Toad Notes Go language--closures

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

The sample code is as follows:

Package Main

Import "FMT"

func Exfunc (nint)func() {

sum:=n

a:=func() {// assigns the anonymous function as a value to variable a(Go does not allow function nesting.)

// However you can use anonymous functions to implement nested functions)

FMT. Println (sum+1)// call a variable outside this function

}// There is no () anonymous function is not executed immediately

returna

}

func Main () {

myfunc:=exfunc (ten)

myFunc ()

myanotherfunc:=exfunc ()

myanotherfunc ()

myFunc ()

myanotherfunc ()

}

Execution results are as follows

11

21st

11

21st

Conditions in which the closure function appears:

1. The nested function refers to an external variable that is not the function, and the external variable is not a "global variable"

2. The nested function is isolated (returned by the parent function or assigned to a separate individual).

The parent function where the referenced variable resides has ended.

Objects are data that is attached to the behavior, and closures are data-attached behaviors.

Friendship Link

Http://www.cnblogs.com/Jifangliang/archive/2008/08/05/1260602.html

Http://blog.sina.com.cn/s/blog_487109d101018fcx.html

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.