In Deep Defer we explained how defer works in the code, and in this article we address a question we left behind in the previous article.

When was defer called

When we used defer, we knew that defer was usually used to free up IO resources, but if we did something else with defer, the program might run differently than we expected. Here are some examples to verify the order in which defer and return are executed.

Is defer executed after the return?

package main

import (
	"log"
)

func main(a) {
	c := test()
	log.Println("main", c)
}
func test(a) int {
	a:=1
	log.Println(a)
	defer func(a) {
		a = 2
		log.Println("defer", a)
	}()
	return a
}

# out
test 1
defer 2
main 1
Copy the code

In this example, we defined a variable ain the test method and returned the value of a at the end of the function. In the main function, we defined a variable C to receive the value. In the test method, we modified the value of a using the defer stack.

From the results in this example, it is concluded that defer is executed after the return.

Does defer execute before return?

We rewrite the above example with a named return value:

package main

import (
	"log"
)

func main(a) {
	a := test()
	log.Println("main", a)
}
func test(a) (a int){
	a=1
	log.Println(a)
	defer func(a) {
		a = 2
		log.Println("defer", a)
	}()
	return a / / 1
}

# out
test 1
defer 2
main 2
Copy the code

Does it feel like a slap in the face? If we had followed the conclusion that defer was executed after the return, we would have returned the value of A at the time, and instead of printing a 1, we would have printed a 2 in Main.

Who executes first, defer or return?

The discussion is too long, so let’s start with “Who will defer or Return first?”