源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-03-12 00:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:简单了解Go语言中函数作为值以及函数闭包的使用
[b]函数作为值[/b] Go编程语言提供灵活性,以动态创建函数,并使用它们的值。在下面的例子中,我们已经与初始化函数定义的变量。此函数变量的目仅仅是为使用内置的Math.sqrt()函数。下面是一个例子:
[u]复制代码[/u] 代码如下:
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

[b]函数闭包 [/b]Go编程语言支持匿名函数其可以作为函数闭包。当我们要定义一个函数内联不传递任何名称,它可以使用匿名函数。在我们的例子中,我们创建了一个函数getSequence()将返回另一个函数。该函数的目的是关闭了上层函数的变量i 形成一个闭合。下面是一个例子:
[u]复制代码[/u] 代码如下:
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
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部