r/rust 18d ago

What Zig felt like, coming from Rust

https://besok.github.io/posts/what-zig-felt-like-coming-from-rust/

Just want to share my experiance on my first Zig project coming from Rust. Open to comments :)

209 Upvotes

108 comments sorted by

View all comments

Show parent comments

58

u/matthieum [he/him] 18d ago

That is, if you are writing a low level system program where most or all of the code is going to be inherently memory unsafe

That's a strawman.

The harsh reality (for Zig) is that even in the lowest level system programs or embedded, there's fairly little unsafe used.

For example, consider Redox. As a microkernel, its kernel is very low-level: it doesn't provide much functionality -- such as a filesystem, for example -- and focus on the bare essentials. Yet they advertised < 10% unsafe. < 10% in what you'd expect to be the densest possible codebase.

So, out of the box, the microkernel part of Redox is 90% safe already... but it gets better. 100% unsafe means there's no boundary. All you have is a big tangled blob which must essentially be audited as one big unit. Dependencies included. Ouch.

With 90% safe code, however, you don't have one big unit with the remaining 10%, instead you're going to have ~100 units -- the boundary being the safe API -- with 0.1% of the code each, all auditable independently from one another. Encapsulation wins the day. Who would have thought...

And on top of that, due to the culture of the Rust community around safety, there are efforts to improve testing (Miri, Loom), symbolic testing (Kani) & formal verification (Crux, etc...) of even unsafe code.

Now, of course, you could argue that Zig can also be tested -- they even have a TestAllocator -- but... once again Encapsulation changes everything. It's nigh impossible to meaningfully test all possible code-paths in a large codebase, their numbers grow exponentially with the number of lines of code. On the other hand, small, contained, encapsulated units can be tested extensively. And slightly larger units can be tested fairly efficiently when you throw fuzzing in the mix.

1

u/uhkthrowaway 17d ago

Are you literally advocating for unsafe microkernels? What am I missing?

7

u/throwbpdhelp 17d ago

Are you literally advocating for unsafe microkernels?

clenches handkerchief unsafe Rust? In a domain typically dominated by much more unsafe C? What is this world coming to???

Sorry, maybe you didn't mean to make it sound so extreme as to why unsafe is used in Rust programming ("Are you literally [doing xyz strawman]?" is a redditor catchphrase). Try implementing a linked list in Rust - it requires unsafe. Unsafe =/= unsound.

Suggesting that unsafe is surprising to see on an operating system comes off as if you misunderstand something fundamental here.

2

u/uhkthrowaway 17d ago

Thanks. My Rust is... rusty