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! }