Go語言函式作為值

2019-10-16 23:16:51

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