Closed kofj closed 4 years ago
Using defer
outside a function is an extension - compiled Go does not allow it.
Gophernotes instead does, and implements it as follows:
defer
at top level, i.e. outside any block, is executed immediately - not at the end of the celldefer
inside a block is executed when the outermost block completesSo to obtain what you expect, just wrap the code in a block:
import (
"fmt"
"time"
)
func calc(index string, a, b int) int {
time.Sleep(1e9)
ret := a + b
fmt.Println(time.Now().Unix(),"\t",index,"\t", a, "\t", b, "\t", ret)
return ret
}
{
a := 1
b := 2
defer calc("1", a, calc("10", a, b))
a = 0
defer calc("2", a, calc("20", a, b))
b = 1
}
WANT
But, got: