Go編程語言提供靈活性,以動態(tài)創(chuàng)建函數(shù),并使用它們的值。在下面的例子中,我們已經(jīng)與初始化函數(shù)定義的變量。此函數(shù)變量的目僅僅是為使用內(nèi)置的Math.sqrt()函數(shù)。下面是一個例子:
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))
}
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 by 1 and return the same */
fmt.Println(nextNumber())
fmt.Println(nextNumber())
fmt.Println(nextNumber())
/* create a new sequence and see the result, i is 0 again*/
nextNumber1 := getSequence()
fmt.Println(nextNumber1())
fmt.Println(nextNumber1())
}