Hacker News new | ask | show | jobs
by nercury 849 days ago
I am Rust developer. My advice: favor less abstractions. Especially when interfacing with C, you can always make almost 1:1 rust interface. Start with that. Then, when common patterns start to emerge, do the data abstractions first, i.e. define data structures shared by different implementations.

There is no reason why you can't write simple code in Rust. Well, except that it's tempting to over complicate things. Start using traits and generics everywhere, and you will enter meta-programming in generics hell. Soon after, you will start demanding new compiler features to survive there.

2 comments

Great advice, but the resulting one-to-one mapping is not necessarily safe (in terms of Rust), which is in part why people jump early on advanced Rust features. So I would rephrase yours as follows: do not reach for abstractions to achieve safety without much consideration and justification.
I admit I don't know enough about kernel development, but from general experience one common example is resource cleanup.

Say, you have several resources that must be cleaned up in certain order. In C, you would just call the appropriate free functions. When abstracting over that with rust, you have to make an annoying choice:

Do what's in C, don't implement automatic Drop, but mark your functions unsafe. You get leanest zero-cost implementation, it is straightforward to understand, but needs additional maintenance care to prevent bugs.

Wrap resources in unsafe structs that have automatic drop (when goes out of scope). IMO this is a terrible choice, because the maintainer suddenly has to know about which structures have this unsafe cleanup going on. Simple scopes suddenly matter, order of items suddenly matter, it's a mess.

Use reference-counting wrappers to track usage and drop the items when they are no longer in use. Most libraries do this, but it's no longer the leanest possible API.

There might be another choice, to achieve both zero-cost execution and correct cleanup using metaprogramming, be it macros, generics, or both. That's exactly what I fear the most.

Thats why im also keeping an eye out for zig and check how they will develop the next 5 years or so. Hope they don't go so meta programming heavy.
Zig has the especially interesting feature that it can compile C code.
That is more a property of shipping the whole LLVM/Clang package with the zig compiler than anything, though.
Whatever the mechanism, it has big implications for how Zig will be used in practice.
A mechanism available to any language that feels like shipping clang.

It is also how Swift gets its C and Objective-C interop, and will have its C++ interop as well.

Or how the Java Panama project extracts header file information for native interop.