top | item 47084271

(no title)

Zambyte | 9 days ago

Probably closer to defer in Zig than in Go, I would imagine. Defer in Go executes when the function deferred within returns; defer in Zig executes when the scope deferred within exits.

discuss

order

rwmj|9 days ago

This is the crucial difference. Scope-based is much better.

By the way, GCC and Clang have attribute((cleanup)) (which is the same, scope-based clean-up) and have done for over a decade, and this is widely used in open source projects now.

CodesInChaos|9 days ago

I wonder what the thought process of the Go designers was when coming up with that approach. Function scope is rarely what a user needs, has major pitfalls, and is more complex to implement in the compiler (need to append to an unbounded list).

0xjnml|9 days ago

> I wonder what the thought process of the Go designers was when coming up with that approach.

Sometimes we need block scoped cleanup, other times we need the function one.

You can turn the function scoped defer into a block scoped defer in a function literal.

AFAICT, you cannot turn a block scoped defer into the function one.

So I think the choice was obvious - go with the more general(izable) variant. Picking the alternative, which can do only half of the job, would be IMO a mistake.

mort96|9 days ago

I hate that you can't call defer in a loop.

I hate even more that you can call defer in a loop, and it will appear to work, as long as the loop has relatively few iterations, and is just silently massively wasteful.

bashkiddie|9 days ago

I would like to second this.

In Golang if you iterate over a thousand files and

    defer File.close()
your OS will run out of file descriptors

Joker_vD|9 days ago

Well, unless you're on Windows :D Even on Windows XP Home Edition I could open a million file handles with no problems.

Seriously, why is default ulimit on file descriptors on Linux measly 1024?

jibal|9 days ago

defer was invented by Andrei Alexandrescu who spelled it scope(exit)/scope(failure) [Zig's errdefer]/scope(success) ... it first appeared in D 2.0 after Andrei convinced Walter Bright to add it.