Simple analysis of the execution time of Go language defer

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

See Code:

 PackageMainImport("FMT""Runtime")funcGetfunctionname()string{PC: = Make([]UIntPtr, Ten) runtime.Callers(2,PC) F: = runtime.Funcforpc(pc[0])returnF.Name()}funcTestwhendefertorun() (RCint) {defer func() {FMT.Printf("I am defer, RC:%d, at:%s\n", Rc, Getfunctionname()) rc =2       }()//return 1       return func()int{FMT.Printf("I am return, RC:%d, at:%s\n", Rc, Getfunctionname())return1       }()}funcMain() {x: =Testwhendefertorun() fmt.Printf("I am Main, rc:%d, at:%s\n", X, Getfunctionname())}

Program output:

I am return, rc:0, AT:MAIN.TESTWHENDEFERTORUN.FUNC2
I am defer, rc:1, at:main.testwhendefertorun.func1
I am Main, rc:2, At:main.main


The output of the program is verifying the description of the following red text, "func1" is the function that the defer deferred execution, the output shows: the function "

Testwhendefertorun return value of 1 indicates that the delay function is executed after the return value is calculated; main.testwhendefertorun.func1 "indicates the call stack: main --- Testwhendefertorun-->func1; function func1 is the function Testwhendefertorun return to the previous execution, it is possible to conclude

The defer statement is used to defer the execution of a function or method (or an anonymous function that is currently being created), which is executed after the peripheral function or method returns but its return value (if any) is evaluated. This makes it possible to modify the named return value of the perimeter function inside a function that is deferred: "


Note: The previous paragraph of red text quote from: "Go language Programming" Mark Summerfield

Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com

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.