Go language Defer delay code

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go language Defer delay code

Suppose you have a function that opens the file and reads it a few. In such a function, there is often a place to return early. If you do this, you need to close the working file descriptor. This often causes the following code to be generated:

funcReadWrite ()BOOL{file. Open ("File")//Do some work    ifFailurex {file. Close ()return false}ifFailurey {file. Close ()return false} file. Close ()return true}

There are a lot of duplicated code here. To solve this, go has a defer statement. The function specified after defer is called before the function exits.

The above code can be rewritten as follows. Placing the close corresponding to open will make the function more readable and robust.

funcReadWrite ()BOOL{file. Open ("File")deferFile. Close ()//file. Close () is added to the defer list    //Do some work    ifFailurex {return false  //close () is now automatically called}ifFailurey {return false  //Here too}return true  //and here}

You can put multiple functions into the delay list, an example from

for  I: = 0 ; I < 5 ; i++ { Defer  FMT. Printf (, i)} 

Deferred functions are executed in last in, first out (LIFO) order, so the above code prints: 4 3 2 1 0. Using defer can even modify the return value, assuming that named result parameters and function symbols are being used, for example:

defer func(xint) {/* ... */}(5)//Assign a value of 5 to the input parameter x

In this (anonymous) function, you can access any of the named return parameters:

funcF () (retint) {RET is initialized to zerodefer func() {ret++ ret increased to1}()return 0Returned is the1Instead of0! }
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.