In English, defer is deferred, and the Go defer statement also delays the statements that follow it.

What is the delay method? Let’s start with an example:

The function is executed after return but before completion

func returnAndDefer(a) int {
	defer func(a) {
		fmt.Println("defer func called")
	}()

	return func(a) int {
		fmt.Println("return func called")
		return 0(1)}}Copy the code

Execution of the returnAndDefer function will print out on standard output

return func called
defer func called

Copy the code

The function returnAndDefer prints two statements: defer func called and return func called. We found the order in which defer/return was executed by looking at the order in which they were printed. Func (){}() is an anonymous function written in Go language.

Notice the penultimate statement defer func() {} in the returnAndDefer function. When the defer statement is executed, the defer func called anonymous method is not executed immediately. The exact time to execute it is at the end of the execution of the function to which it belongs, after the return of the returnAndDefer function, and before the function ends. That is, fmt.println (“defer func called”) is executed just before the returnAndDefer function actually ends.

This is why the defer statement is named as it is. The defer statement, which executes at the end of a function, is perfect for situations where you must close a file after reading it, or link to a relational database after querying the database, etc. The defer statement guarantees that the resource will be destroyed before the function returns the result to the caller. It is a very convenient and effective insurance measure.

Tuition fees of children’s shoes might as well do the following output

func testReturnAndDefer(a)(t int){
	defer func(a){
		t = t *10} ()return 1
}

Copy the code

TestReturnAndDefer () should have returned 1, but after the return, it was executed by the anonymous function of defer. So t=t*10 is executed, and testReturnAndDefer() returns 10

Multiple deferred, last in, first out

When more than one defer appears, it is a lifO stack relationship, for example:

func manyDefer(a) {
	defer func(a) {
		fmt.Print(1)
	}()

	defer func(a) {
		fmt.Print(2)
	}()

	defer func(a) {
		fmt.Print(3)
	}()
	
	

	defer func(a) {
		fmt.Print(4()})}Copy the code

Execution of the manyDefer function will print 4321 on the standard output, even after traversing the print below

func manyDeferV2(a) {
	for i := 1; i < 5; i++ {
		defer fmt.Print(i)
	}
}

Copy the code

exercises

The so-called light says not to practice false handle type, each warrior hits the answer on the message

func manyDeferV3(a) {
	for i := 1; i < 5; i++ {
		defer func(a) {
			fmt.Print(i)
		}()
	}

	fmt.Println()
	for i := 1; i < 5; i++ {
		defer func(n int) {
			fmt.Print(n)
		}(i)
	}

}

Copy the code