Brother even go language training take you to the actual go case (7) Go Defer

Source: Internet
Author: User
Brother even Go language training course System Design framework includes the basic language of the blockchain go language, blockchain backend technology system, blockchain public chain, blockchain distributed application development and other content, as well as to the final interview guidance and project combat.  The course was carefully built by Tsinghua University's Microsoft Google Teacher team, which lasted half a year and developed together. Godefer defer is used to ensure that a function call is called at the end of the program execution. Typically used for resource cleanup work. Packagemain import "FMT" import "OS"//Suppose we want to create a file, then write the data, and finally close the file Funcmain () {//after using CreateFile to get a file object, we use defer//to invoke The method of closing the file CloseFile, this method will be executed in the main function///Finally, that is, after WriteFile completes F:=createfile ("/tmp/defer.txt")//windows Use this statement//f:= CreateFile ("D:\\temp\\defer.txt") Deferclosefile (f) WriteFile (f)} funccreatefile (pstring) *os. file{FMT. PRINTLN ("Creating") F,err:=os. Create (p) iferr!=nil{Panic (Err)} RETURNF} funcwritefile (F*os. File) {fmt. Println ("writing") Fmt. Fprintln (F, "Data")} funcclosefile (F*os. File) {fmt. Println ("Closing") F.close ()} Run results creating writing closing use defer to invoke the CloseFile function to ensure that the action to close the file will be executed before the main function ends. 210 Reads
Related Article

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.