Go Language Defer usage Example analysis _golang

Source: Internet
Author: User

The example in this article describes the go language defer usage. Share to everyone for your reference. The specific analysis is as follows:

Defer: When you call a function that is defer, you delay execution until the function is returned, and when the function is returned, a resource must be released, which is a different but effective way of handling. Traditional examples include unlocking the mutex or closing the file.

There are two advantages to delaying a function: one is that you will never forget to close the file, and this error often occurs when you add a return path to the edit function afterwards. The second is to close and open together, more clearly than at the end of the function.

Copy Code code as follows:
/**
* Created with IntelliJ idea.
* To change this template use File | Settings | File Templates.
* Name:defer
*/
Package Main
Import (
"FMT"
"OS"
"Log"
"IO"
)
Returns the contents of a file as a string
Func Contents (FileName string) (string) {
Open File
F, err: = OS. Open (filename)
If Err!= nil {
Log. Printf ("%s", err)
}
Fmt. Println ("Close before >", f)
If f. Close is finished when it is executed here. So use defer delay to execute
He should be in F. Read () Execute after receiving (I personally understand)
Defer F.close ()
Fmt. PRINTLN ("Close post >", f)
var result []byte
BUF: = Make ([]byte, 100)
for {
N, Err: = F.read (buf[0:])
result = Append (result, buf[0:n] ...)
If Err!= nil {
If err = = Io. EOF {
Break
}
Log. Printf ("Closed f>%s not received", err)//If f closes early, print
}
}
return string (Result)
}
Func Main () {

FileURL: = os. Getenv ("Home")
FileName: = fileurl+ "/test.txt"
Fmt. PRINTLN (Contents (filename))
}

We can make better use of the features that are delayed execution functions

Copy Code code as follows:
/**
* Created with IntelliJ idea.
* To change this template use File | Settings | File Templates.
* Name:defer
*/
Package Main
Import (
"FMT"

)
Func trace (s string) string {
Fmt. Println ("Entering:", s)
return s
}
Func un (s string) {
Fmt. Println ("Leaving:", s)
}
Func A () {
Defer UN (trace ("a"))
Fmt. Println ("in a")
}
Func B () {
Defer UN (trace ("B"))
Fmt. Println ("in B")
A ()
}
Func Main () {
B ()
}

I hope this article will help you with your go language program.

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.