go的闭包

点击查看代码
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, 此处的参数index没有使用上,所以会出问题,
func testClosure6(){
	for i :=0; i<5; i++ {
		go func(index int){
			fmt.Println(i)
		}(i)
	}
	time.Sleep(time.Second)
}

func testClosure7(){
	for i :=0; i<50000; i++ {
		go func(i int){
			fmt.Println(i)
		}(i)
	}
	time.Sleep(time.Second)
}

func main(){
	//testClosure1()
	//testClosure3()
	//testClosure4()
	//testClosure5()
	testClosure6()  // 这个问题不知道怎么改
        testClosure7()
}

testClosure6() 输出:

点击查看代码
2
5
5
2
5
posted @ 2022-03-06 18:15  ty1539  阅读(24)  评论(0编辑  收藏  举报