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