This is a creation in Article, where the information may have evolved or changed.
Common pitfalls and pitfalls of Go language (defer)
Example one: Defer and closure
May I ask the following code snippet
Func foo (a, b int) (i int, err error) { defer FMT. PRINTLN (ERR) if b = = 0 { err = errors. New ("Divided by zero!") Return } i = A/b return}
When calling foo (1, 0), what does the above code output? What is the value of the variable err? I think a lot of go developers will consider the output "divided by zero!". Because we pass the value of parameter B to 0. Defer language to the end of the function is executed. But what is the real result? The answer is output nil. It's unbelievable! If defer is not followed by a closure last execution, we are not getting the latest value. The right approach is
Func foo (a, b int) (i int, err error) { defer func () { fmt. PRINTLN (Err) } () if b = = 0 { err = errors. New ("Divided by zero!") Return } i = A/b return}
Further reading:
Example two: Defer and return
Question: What is the output of the following code?
Func foo () (i int) { i = 0 defer func () { fmt. Println (i) } () return 2}
Answer: Output 2. Explanation: In a function with a named return value (where the named return value is I), the value of I was actually re-assigned to 2 when I executed return 2. So the defer closure output is 2 instead of 1. These are part of the technology share that the seven cow cloud storage team did at the Qcon conference.