This is a creation in Article, where the information may have evolved or changed.
Golang Beginner Series Tutorial-control structure-defer statement
deferA statement is a keyword used to perform a specific function before the function returns. What's the use of it? When programming, resources are usually required allocate/block/lock , but when the program crashes, the code cannot execute to un-allocate/unblock/unlock the resource, which can cause problems such as deadlocks to occur. By using defer statements, you can guarantee that whatever happens, these resources will always be released.
In the following code, assume that you want to perform a series of database operations: Open a database connection and perform an operation. Then assume that the database operation is abnormal and the program returns immediately. If you do nothing, the database connection will persist, and if you use a defer statement, you can ensure that the database connection is closed correctly before the program returns.
PackageMainImport "FMT"funcConnecttodb () {fmt. Println ("OK, connected to DB")}funcDisconnectfromdb () {fmt. Println ("OK, disconnected from DB")}funcDodboperations () {Connecttodb () fmt. Println ("defering the database disconnect.")deferDisconnectfromdb ()//function called here with deferFmt. Println ("Doing some DB operations ...") FMT. Println ("oops! Some crash or network error ... ") FMT. Println ("Returning from function here!")return //terminate The program //Deferred function executed here just before actually returning, even if there is a return or abnormal termination b Efore}funcMain () {dodboperations ()}
......function here!ok, disconnected from db
deferorder of execution of multiple statements
You can declare multiple defer statements. When multiple declarations are made, the order of execution of the LIFO (last in first Out-lifo) is equivalent to a stack. In the following code, first defer fA() , after defer fB() the program returns, the execution order is executed first fB() fA() .
package Mainimport "FMT" func FA () {fmt. Println ( "This is function A" )}func FB () {fmt. Println ( "This is function B" )}func Main () {defer fa () //defer FA called first defer fb () //defer FB called second // Program/this function ends here //deferred functions executed in LIFO Out) Order }
thisisfunction Bthisisfunction A
Golang a magical language, let's make progress together