Hacker News new | ask | show | jobs
by edflsafoiewq 498 days ago
> Zig does have destructors, in a way. It's called defer and errordefer.

defer ties some code to a static scope. Destructors are tied to object lifetime, which can be dynamic. For example, if you want to remove some elements from an ArrayList of, say, strings, the string's would need to be freed first. defer does not help you, but destructors would.

1 comments

That's actually a great argument in favor of Zig over Rust. I assume Rust automatically writes code equivalent to this for you:

``` defer { for (list.items) |str| gpa.free(str); list.deinit(gpa); } ```

When it's spelled out like this, it becomes obvious to the reader that maybe this is the wrong allocation strategy. Maybe the whole thing should go in an Arena. Or, similarly, maybe there should be an ArrayList that holds all the character data that your string ArrayList indexes into with a u32 (or points to with pointers, if you want to update all the pointers on resize). Regardless, I'd be skeptical of code where each string has a separate lifetime even though all the lifetimes could be tied.

Rust makes classic (bad) allocation strategies automatic. Zig makes good allocation strategies more attractive than classic (bad) allocation strategies.

More succinctly: Rust makes bad code safe, Zig makes good code easy.