Pits anonymous return values with play name return values

In further defer (continued) we enumerated the confusion of anonymous and named return values, and who executes first between defer and return? In the assembly code through the point of view of the answer.

package main

import "log"

func main(a) {
	log.Println(testA())
	log.Println(testB())
}

func  testA(a) int {
	a:=1
	defer func(a) {
		a=2} ()return a
}

func testB(a) (a int) {
	a=1
	defer func(a) {
		a=2} ()return a
}

# out
1
2
Copy the code

Avoid pitfalls: Avoid confusing usage in development

Closure of the pit

package main

import "log"

func main(a){
	for i:=1; i<5; i++{defer func(a) {
			log.Println(i)
		}()
	}
}
# out
5
5
5
5
Copy the code

The correct way to write it

package main

import "log"

func main(a){
	for i:=1; i<5; i++{defer func(a int) {
			log.Println(a)
		}(i)
	}
}

# out
4
3
2
1
Copy the code

Don’t use defer in a loop at development time. The functions defined by defer need to be pushed, and you need to allocate extra memory to store defer, so anything that doesn’t apply to defer in the loop should be avoided

Use functions as arguments to pit

package main

import "log"

func main(a){
	defer log.Println(test())
	log.Println(2)}func test(a) int {
        log.Println(3)
	return 1
}

# out
3
2
1
Copy the code

If the function defined by defer contains function parameters, defer will execute them before pushing them, and the result will be pushed along with the function defined by defer

Os.exit causes defer not to be called

The os.exit function is not often used, but it should be known that it will appear directly at the location of Exit

package main

import (
	"log"
	"os"
)

func main(a){
	defer func(a) {
		log.Println(1)
	}()
	os.Exit(1} # out no outputCopy the code

Avoid pitfalls: Make sure you understand what os.Exit does and use it when appropriate, and use the return end method whenever possible

conclusion

  1. Do not use variables defined outside of defer in the defer function; if you do, try to pass them in
  2. Do not use the defer function in the loop
  3. Do not use functions as arguments in the defer function

Every language has its own disadvantages. In the process of using it, you should be aware of the problems, but try to avoid using it