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