Go - 函式作為值



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
go_functions.htm
廣告
© . All rights reserved.