函數(shù)作為值
Go編程語言提供靈活性,以動(dòng)態(tài)創(chuàng)建函數(shù),并使用它們的值。在下面的例子中,我們已經(jīng)與初始化函數(shù)定義的變量。此函數(shù)變量的目?jī)H僅是為使用內(nèi)置的Math.sqrt()函數(shù)。下面是一個(gè)例子:
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
函數(shù)閉包
Go編程語言支持匿名函數(shù)其可以作為函數(shù)閉包。當(dāng)我們要定義一個(gè)函數(shù)內(nèi)聯(lián)不傳遞任何名稱,它可以使用匿名函數(shù)。在我們的例子中,我們創(chuàng)建了一個(gè)函數(shù)getSequence()將返回另一個(gè)函數(shù)。該函數(shù)的目的是關(guān)閉了上層函數(shù)的變量i 形成一個(gè)閉合。下面是一個(gè)例子:
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
新聞熱點(diǎn)
疑難解答
圖片精選