函數作為值
Go編程語言提供靈活性,以動態創建函數,并使用它們的值。在下面的例子中,我們已經與初始化函數定義的變量。此函數變量的目僅僅是為使用內置的Math.sqrt()函數。下面是一個例子:
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 形成一個閉合。下面是一個例子:
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
新聞熱點
疑難解答