go的閉包
阿新 • • 發佈:2022-03-06
點選檢視程式碼
package main import ( "fmt" "strings" "time" ) func Adder() func(int) int { var x int = 3 return func(d int) int { x += d return x } } func testClosure1(){ f := Adder() ret1 := f(1) fmt.Printf("f(1)>> ret1=%d\n",ret1) ret20 := f(20) fmt.Printf("f(20)>> ret1=%d\n",ret20) f1 := Adder() ret11 := f1(1) fmt.Printf("f1(10)>> ret11=%d\n",ret11) ret201 := f1(20) fmt.Printf("f1(12)>> ret201=%d\n",ret201) } func add(base int) func(int) int { return func(i int) int { base += i return base } } func makeSuffixFunc(suffix string)func(string) string { return func(name string)string { if !strings.HasSuffix(name,suffix){ return name + suffix } return name } } func testClosure3(){ func1 := makeSuffixFunc(".bmp") func2 := makeSuffixFunc(".jpg") fmt.Println(func1("test")) fmt.Println(func2("test")) } func calc(base int)(func(int) int, func(int) int){ add := func (i int) int { base += i return base } sub := func (i int) int { base -= i return base } return add, sub } func testClosure4(){ f1,f2 := calc(10) fmt.Println(f1(1), f2(2)) fmt.Println(f1(3), f2(4)) fmt.Println(f1(5), f2(6)) fmt.Println(f2(7), f1(8)) } func testClosure5(){ for i:=0; i<5; i++ { go func() { fmt.Println(i) }() } time.Sleep(time.Second) } //這樣還是不能修改成打印出正確的i func testClosure6(){ for i :=0; i<5; i++ { go func(index int){ fmt.Println(i) }(i) } time.Sleep(time.Second) } func main(){ //testClosure1() //testClosure3() //testClosure4() //testClosure5() testClosure6() // 這個問題不知道怎麼改 }
testClosure6() 輸出:
點選檢視程式碼
2
5
5
2
5