The practice of defer on Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang defer how to say. The effect is after the function return. Before the function is closed. Keywords to execute in order of filo

On the code:

 PackageMainImport (    "FMT") Func main () {//A ()FMT. Println (c ())//B ()//FMT. Println (d ())}func C () (Iint) {defer func () {i++} () defer FMT. Println ("This:", i)return1}func A () {i:= 0defer FMT. PRINTLN (i) I= i + 1}func B () {var whatever [5]struct{} forI: =Range Whatever {//defer func () {fmt. Println (i)} ()Defer func (nint) {fmt. PRINTLN (N)} (i)}}func D () (Iint) {defer FMT. Println ("Sdad")    return1}

Return of Function C ():

this: 02

Return of Function A ():

0

Return of Function B ():

43210

Return of Function D ():

Sdad1

And then to figure out whether it was executed before or after return.

 Package Main Import (    "FMT") Func main () {    test ()}func test() (int, error) {    defer FMT. Println ("defer")    return to FMT. Println ("Return")}

The output is:

return defer

Enlightened.. Is the one that executes after return.

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.