Function Value Pass
A function is also a value. They can be passed like other values, for example, the function value can be used as a function parameter or a return value.
Package main
Import (
"FMT"
"math"
)
func Compute (fn func (float64, float64) float64) float64 { Return
FN (3, 4)
}
Func Main () {
Hypot: = Func (x, y float64) float64 {return
math. SQRT (x*x + y*y)
}
fmt. Println (Hypot (5)) //Call hypot function, output
FMT. Println (Hypot) //Compute the Hypot function as a parameter to the COMPUTE function, using 3,4 as a parameter call to the Hypot function, the result is 5
FMT. PRINTLN (COMPUTE) (math. Pow)) //Will math. The POW function acts as an argument to the compute function, using 3,4 as the calling math. Pow function parameter call, the result is Bayi
}
Closure of functions
Package main
Import "FMT"
func adder (i int) func (int) int {
sum: = I return
func (x int) int {
sum = x return
sum
}
}
Func adder2 (i int) func () int {
sum: = I return
func () int {return
sum
}
}
func main () {
fmt. Printf ("%t\n", Adder2 (3)) //The type returned here is a function func () int
FMT. Println (Adder2 (3) ()) //Use this method to return to the final result 3
pos, neg: = Adder (1), adder (1) for
I: = 0; i < 3; i++ {
FMT.P Rintln (
pos (i),
neg ( -2*i), //This is also the way the closure function is invoked, resulting in 1 1,2-1,4-5
)
}