Comment by marcodiego

Comment by marcodiego 8 days ago

3 replies

Never used it, but I follow wg14, ISO's workgroup that maintains the C programming language specification. From there, it looks like defer is one of the most important improvements since the go programming language and I've seen a good number of examples were it prevents mistakes, makes the code more readable and avoids use of goto.

I can only hope it 'infects' other languages.

iainmerrick 8 days ago

But Go's defer operates at function scope, which strikes me as the same kind of unfortunate mistake as JavaScript's "var" hoisting.

What we want everywhere is block-scoped defer, right?

  • int_19h 6 days ago

    It really depends. If you e.g. allocate items inside a loop to build up an array to later do something on that, you'd want defer to run only for the allocated items (and thus the statement needs to be inside the loop body), but deallocation should only happen once the array is actually used.

    If we're going to have that kind of semi-manual resource management, anyway, it would be better to have labelled blocks and the corresponding defer-like statement that can reference them. Something like:

       outer: {
          ...
          inner: {
             defer close(x) after outer;
          }
       }
  • bsder 6 days ago

    > What we want everywhere is block-scoped defer, right?

    Not always. Block-scoped defer makes allocating inside "if blocks" a pain.

    The flip side is that function-scoped is a pain to implement in a non-GC language.