This article describes the Go Language delay function defer usage. Share to everyone for your reference. The specific analysis is as follows:
Defer in the declaration will not be executed immediately, but after the function return, followed by the FILO (advanced out) principle in order to execute each defer, generally used for exception handling, releasing resources, cleaning data, logging and so on. It's a bit like a destructor of object-oriented language, elegant and concise, one of the highlights of Golang.
Code 1: Understanding the order in which defer is executed
Copy Code code as follows:
Package Main
Import "FMT"
FUNC fn (n int) int {
Defer func () {
n++
Fmt. Println ("3st:", N)
}()
Defer func () {
n++
Fmt. Println ("2st:", N)
}()
Defer func () {
n++
Fmt. Println ("1st:", N)
}()
return n//didn't do anything
}
Func Main () {
Fmt. Println ("function return value:", fn (0))
}
Output:
1st:1
2st:2
3st:3
function return Value: 0
Code 2: Classic Application examples
Copy Code code as follows:
Func copyfile (DST, src String) (w Int64, err error) {
Srcfile, err: = OS. Open (SRC)
If Err!= nil {
Return
}
Defer srcfile.close ()//Every time you apply for a resource, be used to applying for a defer to close the resource immediately so that you don't forget to release the resource.
Dstfile, err: = OS. Create (DST)
If Err!= nil {
Return
}
Defer Dstfile.close ()
Return IO. Copy (Dstfile, Srcfile)
}
Another important feature of defer is that even if the function throws an exception, it is executed. This will not cause the resource to be freed because of an error in the program.
I hope this article will help you with your go language program.