Go Learning Note: Deferred execution function defer

Source: Internet
Author: User
Tags bool

There is a good design in the go language, the deferred (defer) statement, where you can add multiple defer statements to a function. When the function executes to the last, these defer statements are executed in reverse order, and finally the function returns. Especially when you are doing some open resources operation, encountered errors need to return early, before returning you need to close the corresponding resources, otherwise it is easy to cause problems such as resource leakage. As shown in the following code, we generally write open a resource that works like this:

Func ReadWrite () bool {
    file. Open ("file")
    //Do some work
    if Failurex {
        file. Close ()
        return False
    }

    if Failurey {
        file. Close ()
        return False
    }

    file. Close ()
    return True
}

We see a lot of duplicated code on it, and the go defer effectively solves this problem. With it, not only is the amount of code reduced a lot, but the program becomes more elegant. The function specified after defer is called before the function exits.

Func ReadWrite () bool {
    file. Open ("file")
    defer file. Close ()
    if Failurex {
        return false
    }
    if Failurey {
        return false
    }
    return True
}

If there are many calls to defer, then defer is in LIFO mode, so the following code will output 4 3 2 1 0

For I: = 0; I < 5; i++ {
    defer FMT. Printf ("%d", i)
}
Related Article

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.