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:
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: