Go 語言函數作為實參

Go 函數Go 函數

Go 語言可以很靈活的創建函數,並作為另外一個函數的實參。以下實例中我們在定義的函數中初始化一個變數,該函數僅僅是為了使用內置函數 math.sqrt(),實例為:

實例

package main

import (
   "fmt"
   "math"
)

func main(){
   /* 聲明函數變數 */
   getSquareRoot := func(x float64) float64 {
      return math.Sqrt(x)
   }

   /* 使用函數 */
   fmt.Println(getSquareRoot(9))

}

以上代碼執行結果為:

3

Go 函數Go 函數