This is a creation in Article, where the information may have evolved or changed.
Defer is not executed immediately at the time of Declaration, but after the function return, followed by the FILO (advanced out) principle of each defer, typically used for exception handling, freeing up resources, cleaning up data, logging, and so on. This is a bit like the object-oriented language of the destructor, elegant and concise, is one of the highlights of Golang.
Code Listing 1: Understanding the order of execution of defer
Package Mainimport "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//Do nothing}func main () {FMT. Println ("function return value:", fn (0))}
Output:
1st:1
2st:2
3st:3
function return Value: 0
Code Listing 2: Classic application examples
Func CopyFile (DST, src String) (w Int64, err error) {srcfile, err: = OS. Open (SRC) if err! = nil { return} defer Srcfile.close ()//each time you request a resource, be accustomed to immediately apply for a defer close resource so that you do not forget to release the resource Dstfile, err: = O S.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 will be executed. This prevents the resource from being freed because of an error in the program.