Go language defer use

Source: Internet
Author: User

Defer

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 go defer solves this problem effectively. With it, not only is the amount of code reduced a lot, but the program becomes more elegant. The defer function specified later is called before the function exits.

BOOL {    file. Open ("file")    defer file. Close ()    if  failurex {        returnfalse    }     If  failurey {        returnfalse    }      Returntrue}

If there are many calls, then the last-in- defer defer first-out mode is used, so the following code will output4 3 2 1 0

 for 0 5; i++ {    defer FMT. Printf ("", i)}

The first impression that defer gave me was that, like in Java,

try {

}finally {

}

My current understanding is that in the function block using defer, is the function corresponding to a stack space, advanced and out. Call the stack at the end of the function to start the defer operation.

If an object is created that consumes memory and needs to be closed in a timely manner, defer cannot be as accurate as try Finnaly.

Package Mainimport "FMT" Import "time" type User struct {        username string}func (this *user) Close () {        fmt. Println (this.username, "Closed!!!")} Func Main () {        u1: = &user{"Jack"}        defer U1. Close ()        u2: = &user{"Lily"}        defer U2. Close () Time        . Sleep (Ten * time. Second)        FMT. PRINTLN ("Done!")} [Email protected] goroutine]$

  

[email protected] goroutine]$ go run defertest1.go
Done!
Lily Closed!!!
Jack Closed!!!
[Email protected] goroutine]$

In fact, the thread sleep 10 seconds, U1, and U2 can already close (), but need to rely on the end of the main () function in order to defer execution.

Then try adding an internal code area to defer:

"FMT""Time"type User struct {        username string}func (this *user) Close () {        fmt. Println (This.username, "Closed!!!" }func Main () {        {                ///Even if the code is fast-range, it still needs the main function body to end before executing defer                u1:= &user{"Jack"}                defer U1. Close ()        }        u2:= &user{"Lily"}        defer U2. Close () Time        . Sleep (ten * time. Second)        FMT. Println ("Done!" )}

Done!
Lily Closed!!!
Jack Closed!!!
[Email protected] goroutine]$

Still defer's execution in done! After. So how do you get to the exact close of try finally?

Package Mainimport"FMT"Import"Time"type User struct {username String}func (this *user) Close () {fmt. Println (This.username, "Closed!!!")}func Main () {u1:= &user{"Jack"} f (U1)//In such a way that U1 does not rely on the execution of the main function//in such a way that U2 does not rely on the execution of the main function U2:= &user{"Lily"}//M:=func () {//defer U2. Close ()////U2 do somthing/////M () func () {;U2. Close ()} ()func () {defer U2. Close ()//U2 do somthing} () time. Sleep (Ten * time. Second) fmt. PRINTLN ("Done!")}func F (U *user) {defer u.close ()//U1 do gomething}

[email protected] goroutine]$ go run defertest3.go
Jack Closed!!!
Lily Closed!!!
Done!

The use of such a method, depending on the unreasonable, but there is the need for existence. In most cases, it can be used in situations such as u1,u2 that consume very much memory, or the CPU, and then execute the time process without too many associations. It retains the functional characteristics of the defer and satisfies the conditions of precise control of the range!

Go language defer use

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.