Go by Example:closures

Source: Internet
Author: User

The go language supports anonymous functions. Anonymous functions can form function closures. Anonymous functions are useful when you want to define an inline function that does not need to be named.

Package Mainimport "FMT"//This "INTSEQ" function returns another anonymous function defined inside the INTSEQ,//The returned anonymous function has wrapped the variable i, thus forming a closure func intseq () func () int {    I: = 0    return func () int {        i + = 1        return i    }}func main () {    //We call the INTSEQ function and <span the result style= "F Ont-family:arial, Helvetica, Sans-serif; > (function) </span><span style= "font-family:arial, Helvetica, Sans-serif;" > Assign to a function nextint,</span>    //The Nextint function has its own I variable, which is updated each time the call is called.    //The initial value of I here is determined by the time the intseq is called.    Nextint: = Intseq ()    //Call several nextint to see the effect of the closure    FMT. Println (Nextint ())    FMT. Println (Nextint ())    FMT. Println (Nextint ())    //In order to confirm that the state of the closure is independent of the INTSEQ function, create one.    newints: = Intseq ()    FMT. Println (Newints ())}
Output
<strong>$ Go Run closures.go1231</strong>

In the next section, we will learn the last feature of the function: recursion.

Next example: Go by Example:recursion.

English original


Go by Example:closures

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.