golang-15- 函數高級特性


1、匿名函數就是沒有名字的函數,它以函數字面量的方式在行內進行聲明。

擁有同樣的函數簽名形式,同樣擁有參數列表和返回值

<code>import ("fmt""math")func main(){/* 聲明函數變量 */getSquareRoot := func(x float64) float64 {return math.Sqrt(x)}/* 使用函數 */fmt.Println(getSquareRoot(9))   //結果為 3}/<code>


2、Go 語言可以很靈活的創建函數,並作為另外一個函數的實參,也就是說匿名函數可以直接賦給一個變量。

我們在定義的函數中初始化一個變量,該函數僅僅是為了使用內置函數 math.sqrt()

<code>func adder() func(int) int {sum := 0return func(x int) int {sum += xreturn sum}}func main() {  ////函數adder返回一個閉包。每個閉包都被綁定到其各自的sum變量上pos, neg := adder(), adder()for i := 0; i < 10; i++ {fmt.Println(pos(i),neg(-2*i),)}}// 0 0// 1 -2// 3 -6// 6 -12// 10 -20// 15 -30// 21 -42// 28 -56// 36 -72// 45 -90// /<code>

3、函數的閉包

Go 函數可以是閉包的。閉包是一個函數值,它來自函數體的外部的變量引用。 函數可以對這個引用值進行訪問和賦值;換句話說這個函數被“綁定”在這個變量上。

<code>func adder() func(int) int {sum := 0return func(x int) int {sum += xreturn sum}}func main() {  ////函數adder返回一個閉包。每個閉包都被綁定到其各自的sum變量上pos, neg := adder(), adder()for i := 0; i < 10; i++ {fmt.Println(pos(i),neg(-2*i),)}}// 0 0        解析  pos(0)中  0+0=0    neg(0)中     0+0=0// 1 -2      解析   pos(1)中  0+1=1   neg(1)中      0+-2=-2// 3 -6      解析   pos(2)中  1+2=3   neg(2)中      -2+-4=-6// 6 -12    解析   pos(3)中  3+3=6   neg(3)中      -6+--6=--12// 10 -20// 15 -30// 21 -42// 28 -56// 36 -72// 45 -90/<code>

4、如果一個函數需要傳入若干不確定個數的參數,就可以使用"..."的方式來表達這若干個參數

<code>func test(args ...string){    fmt.Printf("%T", args) //打印類型是數組}/<code>


golang-15- 函數高級特性


分享到:


相關文章: