Latest web development tutorials

Go 語言函數作為值

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函數