C for Rust Programmers(bd103.dev) |
C for Rust Programmers(bd103.dev) |
> C's error handling story, in comparison, is straight up tragic. It seems to boil down to functions returning a "magic integer" like -1 or a null pointer to signal there was an error.
In C23 you can add the [[nodiscard]] attribute to the declaration of an enum or struct type, then at every call site of every function that returns said type, the C compiler will emit a warning if the result is unused. Instruct the compiler to treat warnings as errors and you can't ignore them.
Interestingly, Zig's error handling is conceptually C like, but limited to integer-like enums (no structs). It's basically a union of error integer code and success result. However, despite being limited to integers, Zig has dedicated compiler machinery for this so there's idiomatic consistency in Zig error handling.
I hope it can be useful for writing C ABI bindings especially for things like CLAP audio plugins. Writing C ABI plugins in Rust is needlessly painful. Crystal has a much easier way to write C bindings.