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.