How to implement something that works as a defer statement from python?
Snooze a function call onto the stack. When the function containing the defer statement is returned, the calls to the deferred function are inverted and executed one after the other, in the area in which the defer statement originally lay. Deferred statements look like function calls, but are not executed until they are unloaded.
An example of using this method:
func main() { fmt.Println("counting") var a *int for i := 0; i < 10; i++ { a = &i defer fmt.Println(*a, i) } x := 42 a = &x fmt.Println("done") }
Outputs:
counting done 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0
Usecase example:
var m sync.Mutex func someFunction() { m.Lock() defer m.Unlock()
python go deferred
Filip haglund
source share