Defer will often be used, but this pit is not for me to step on, because I usually do not use the name return parameters, one is not much necessary, and the second increases the difficulty of reading code. However, this pit can be a good way to understand the keyword return, so this is recorded here.
func test() (res int) { res = 1 defer func() { res++ }() return 0}
Silently in the heart to run this program, the first return value should be 0, otherwise, return is not an atomic operation. Divided into, assignment and return two operations, <return 0> is actually equivalent to <res = 0, return res>, and defer is executed after the assignment operation, so this function is equivalent to:
func test() (res int) { res = 1 res = 0 //赋值 func() { res++ //defer }() return res //返回}
Let's look at an example:
func test() (res int) { tmp := 1 defer func() { tmp++ }() return tmp}
According to the experience of the previous analysis of this program, Tmp=1, and then returned to add 1, it should be 2. In fact, it's wrong to note that the return value is named res, not the Tmp,defer change can only be TMP. This function can be equivalent to:
func test() (res int) { tmp := 1 res = tmp func() { tmp++ }() return }
The result should be 1.