Go language delay function defer usage analysis _golang

Source: Internet
Author: User
Tags exception handling

This article describes the Go Language delay function defer usage. Share to everyone for your reference. The specific analysis is as follows:

Defer in the declaration will not be executed immediately, but after the function return, followed by the FILO (advanced out) principle in order to execute each defer, generally used for exception handling, releasing resources, cleaning data, logging and so on. It's a bit like a destructor of object-oriented language, elegant and concise, one of the highlights of Golang.

Code 1: Understanding the order in which defer is executed

Copy Code code as follows:
Package Main

Import "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//didn't do anything
}

Func Main () {
Fmt. Println ("function return value:", fn (0))
}


Output:

1st:1
2st:2
3st:3
function return Value: 0

Code 2: Classic Application examples

Copy Code code as follows:
Func copyfile (DST, src String) (w Int64, err error) {
Srcfile, err: = OS. Open (SRC)
If Err!= nil {
Return
}
Defer srcfile.close ()//Every time you apply for a resource, be used to applying for a defer to close the resource immediately so that you don't forget to release the resource.

Dstfile, err: = OS. 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 is executed. This will not cause the resource to be freed because of an error in the program.

I hope this article will help you with your go language program.

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.