Common pitfalls and pitfalls of Go language (defer)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.