您现在的位置是:网站首页> 编程资料编程资料
简单了解Go语言中函数作为值以及函数闭包的使用_Golang_
                    
                
                2023-05-26
                571人已围观
            
简介 简单了解Go语言中函数作为值以及函数闭包的使用_Golang_
函数作为值
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
                                
                                                        
                                
                                                        
                                
                                                        
    