Hacker News new | ask | show | jobs
by scoopr 454 days ago
Oh well, maybe we'll soon have `defer`? [0]

[0] https://thephd.dev/c2y-the-defer-technical-specification-its...

1 comments

That's sad. Having migrated from C++ to golang a few years ago, I find defer vastly inferior to C++ destructors. Rust did it right with its drop trait, I think it's a much better approach
The proposed C defer is scope-based unlike Go. So in the spirit of OP article, you can basically hand roll not only C++ destructor as defer {obj.dtor()} but also Rust Drop as defer {obj.notmoved() ? Drop()}
What do you mean defer isn't scope based in Go?

(not super experienced Go developer)

In Go, defers are function scoped not block scoped.
I mean, you just write all your scopes as `(func() { })()` in go, and it works out fine.

Adding `func() {}()` scopes won't break existing code usually, though if you use 'break' or 'continue' you might have to make some changes to make it compile, like so:

https://go.dev/play/p/_Gq4QYtyMmp

see, no other issues, works exactly like you'd expect

Right, that makes more sense.
Although that is true, the author has expounded at lengths on the unsuitability of RAII to the C programming langage, and as a big fan of RAII the explanations were convincing.
Even Zig which is extremely against "Hidden control flow" (so no operator overloading, etc.) added in the "defer" feature.
Destructors/drop have issues though:

* cannot return errors/throw exceptions * cannot take additional parameters (and thus do not play well with "access token" concepts like pyo3's `Python` token that proves the GIL was acquired -- requiring the drop implementation to re-acquire the lock just in case)

I think `defer` would be a better language construct than destructors, if it's combined with some kind of linear types that produce compiler errors if there is some code path that does not move/destroy the object.

What's "drop trait" for C? There are no any traits in C.
Parent post said Rust.

edit: TIL: Looks like the [drop trait][1] is an opt-in destructor that the Rust compiler understands.

[1]: https://doc.rust-lang.org/nomicon/dropck.html