4 ms·
One benefit of function based defer is that you can use anonymous functions to create hacky block-based defers. If the language only has block based defers the
by eknkc 6y ago
One benefit of function based defer is that you can use anonymous functions to create hacky block-based defers.
If the language only has block based defers then that's it. You have that and only that.
What if I create a resource in an if block and want to defer closing it when the function ends?
- dthul 6y agoDepending on how the defer implementation looks like the same could be achieved with block-level defer by having the defer's "owner" (e.g. some object with RAII semantics) in the outer scope.
- bbatha 6y agoYou can get function based defers pretty easily with block ones too func Deferred() { defers := []func(){} defer func() { for _, def := range defers { def() } } for { cleanup, done := work() defers = append(defers, cleanup) if done { break } } } Edit: this is how defers were implemented in the compiler until a few versions ago and will fall back to this if you defer in a loop