logoalt Hacker News

Zambyteyesterday at 5:50 AM4 repliesview on HN

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.


Replies

rwmjyesterday at 8:16 AM

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.

CodesInChaosyesterday at 10:02 AM

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).

show 2 replies
bashkiddieyesterday at 9:35 AM

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
show 1 reply
jibalyesterday at 2:30 PM

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.