Closure of Golang Learning

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

An anonymous function cannot exist independently, but can be assigned to a variable, that is, to hold the address of the function into the variable: and fplus := func(x, y int) int { return x + y } then invoke the function through the variable name:fplus(3,4)。

Of course, the anonymous function can also be called directly: func(x, y int) int { return x + y } (3, 4) .

func () {    = 0.0 for     i: = 1; I <= 1e6; i++ {        + = I    }} ()

The first pair of parentheses that represent the argument list must be next to the keyword func , because the anonymous function has no name. The curly braces {} cover the function body, and the last pair of parentheses indicate a call to the anonymous function.

Use defer to modify method return values in conjunction with anonymous functions (closures):

"FMT"int, str string) {    defer func () {        ret+ +    } ()    defer func () {        + = ("##########")    } (    )return , "111"}func Main () {    fmt. Println (f ())    }

Print output:

23 111 ##########

Closure instances:

 package mainimport  "FMT" func Main () {  var  F = Adder () fmt. Print (f ( 1), "-" ) fmt. Print (f (), "-" ) fmt. Print (f ( 300))}func Adder () func ( int ) int   { var  x int  return  func (Delta int ) int   {x  += Delta  return   X}}  

The first call to the Adder function returns a func (int) int function, and the value of the local variable x is incremented when re-tuned, and the final output is:

1  + 321

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.