Go編程語言提供了靈活性,可以即時創建函數並將其用作值使用。在下面的示例中,我們已經使用函數定義初始化了一個變數。 這個函數變數的用途僅僅是使用內置的math.sqrt()
函數。 以下是示例:
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))
}
當上述代碼編譯和執行時,它產生以下結果:
3