Defer's pit and return's understanding

Source: Internet
Author: User

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.

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.