Simply understand the use of functions as values and function closures in go language _golang

Source: Internet
Author: User
Tags anonymous

function as a value

The Go programming language provides the flexibility to dynamically create functions and use their values. In the following example, we have the variables defined with the initialization function. The purpose of this function variable is simply to use the built-in math.sqrt () function. Here is an example:

Copy Code code as follows:

Package Main

Import (
"FMT"
"Math"
)

Func Main () {
/* Declare a function variable * *
Getsquareroot: = func (x float64) float64 {
return Math. SQRT (x)
}

/* Use the function * *
Fmt. Println (Getsquareroot (9))

}


When the above code is compiled and executed, it produces the following results:

3

function closures
The Go programming language supports anonymous functions that can be closed as functions. When we want to define a function inline without passing any name, it can use an anonymous function. In our example, we created a function getsequence () to return another function. The purpose of the function is to turn off the upper function of the variable i form a closure. Here is an example:

Copy Code code as follows:

Package Main

Import "FMT"

Func getsequence () func () int {
I:=0
return func () int {
I+=1
return I
}
}

Func Main () {
/* Nextnumber is now a function with I as 0 * *
Nextnumber: = Getsequence ()

/* Invoke Nextnumber to increase I through 1 and return the same * *
Fmt. Println (Nextnumber ())
Fmt. Println (Nextnumber ())
Fmt. Println (Nextnumber ())

/* Create a new sequence and the result, I is 0 again*/
NextNumber1: = Getsequence ()
Fmt. Println (NextNumber1 ())
Fmt. Println (NextNumber1 ())
}


When the above code is compiled and executed, it produces the following results:

1
2
3
1
2

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.