Defer usage analysis of Go language delay function

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

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.