Golang Beginner Series Tutorial-control structure-defer statement

Source: Internet
Author: User
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

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.