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.