[Go] Closure function

Procedure before improvement

package main

import "fmt"

func main() {
    
    
	var p2,progress int
	//获得武松和鲁达各自的“闭包内层函数”
	//闭包的作用是保存“各自的内层函数状态”
	f1 := GetDoTaskFunc()
	f2 := GetDoTaskFunc()
	//交错的执行任务
	progress = f1("武松",13)
	p2 = f2("鲁达",12)
	progress = f1("武松",13)
	p2 = f2("鲁达",13)
	progress = f1("武松",1)
	p2 = f2("鲁达",13)
	//查看各自的状态
	//各自的任务被保存在各自的闭包中
	fmt.Print("鲁达的进度说:",p2)
	fmt.Println("二哥的进度是",progress)


	//f1 := GetDoTaskFunc()
}

func GetDoTaskFunc() func(name string,hours int) (progress int) {
    
    
	var progress int = 0
	f := func(name string,hours int) int {
    
    
		fmt.Printf("%s头领带队行军%d的小时\n",name,hours)
		progress += hours
		return progress
	}
	return f
}

Improved program

package main

import "fmt"

func main() {
    
    
	tf1 := GetTaskFunc("武松")
	tf2 := GetTaskFunc("李逵")

	p1 := tf1(13)
	p2 := tf2(14)
	p1 = tf1(10)
	p2 = tf2(18)
	fmt.Println("武松的进度:",p1)
	fmt.Println("李逵的进度:",p2)
}

func GetTaskFunc(name string) func(hours int) (progress int) {
    
    
	var progress = 0
	ExcuteTask := func(hours int) int {
    
    
		fmt.Printf("%s带队行军%d小时\n", name, hours)
		progress += hours
		return progress
	}
	return ExcuteTask
}

Guess you like

Origin blog.csdn.net/qq_36045898/article/details/113804502