华域联盟 Golang 简单了解Go语言中函数作为值以及函数闭包的使用

简单了解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编程语言支持匿名函数其可以作为函数闭包。当我们要定义一个函数内联不传递任何名称,它可以使用匿名函数。在我们的例子中,我们创建了一个函数getSequence()将返回另一个函数。该函数的目的是关闭了上层函数的变量i 形成一个闭合。下面是一个例子:

复制代码 代码如下:

package main

import "fmt"

func getSequence() func() int {
   i:=0
   return func() int {
      i+=1
   return i 
   }
}

func main(){
   /* nextNumber is now a function with i as 0 */
   nextNumber := getSequence() 

   /* invoke nextNumber to increase i by 1 and return the same */
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
   fmt.Println(nextNumber())
  
   /* create a new sequence and see the result, i is 0 again*/
   nextNumber1 := getSequence() 
   fmt.Println(nextNumber1())
   fmt.Println(nextNumber1())
}

当上述代码被编译和执行时,它产生了以下结果:

1
2
3
1
2

本文由 华域联盟 原创撰写:华域联盟 » 简单了解Go语言中函数作为值以及函数闭包的使用

转载请保留出处和原文链接:https://www.cnhackhy.com/110107.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

深入剖析Go语言编程中switch语句的使用

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们