4 ms·
I think the reason is much simpler: block-scoped defer isn't useful if you statements appear in a nested construct. Example: fd := OpenSocket(...); if
by sltkr 6y ago
I think the reason is much simpler: block-scoped defer isn't useful if you statements appear in a nested construct. Example:
fd := OpenSocket(...);
if fd != 0 {
defer CloseSocket(fd);
}
// do stuff
For the same reason, Go's defer cannot be implemented without dynamic allocations. For example, how would you implement:
func foo(int n) void {
for i := 0; i < n; i++ {
var res = bar(n);
defer fmt.Println(res);
}
}
This calls bar(0), bar(1), etc. then prints the results of bar(n - 1), bar(n - 2), etc. There is no way to implement this without some way to store the intermediate values.
- ttt0 6y agoCompiler should be able to figure out at compile time whether the dynamic allocation is needed. But maybe the Go compiler already does this, I don't know.
- sltkr 6y agoTrue, I was talking about the general case. This is a bit similar to local variables: they have to be allocated on the heap in the general case, but Go uses escape analysis to determine which local variables can safely be allocated on the stack instead, which is much cheaper.