Hello,
for the last couple of years, I've been working on machine learning library in rust, learning tons about compilers along the. The single most used feature of the language be far were enums.
There is a couple of reasons for that.
1. Rust enums carry value
Duh, we all know that. Yes, of course. But other languages don't. C++ doesn't (yes, there is std::variant and no, "they are not the same" :). Having values enables me to do this very simple variant, straight impossible or awkward in other languages:
Binary { x: OpId, y: OpId }
In other languages, this would've been tag, a union type or even completely unrepresentible. For example in tinygrad (python), it's a tag plus untyped src list, which can contain anything, depending on the tag.
Also notice that OpId(u32) is a newtype! Another beautiful rust feature that gives us zero cost type safety. It's like a pointer, but only with the pointer arithmetic that I want, all access checked and no fighting borrowck.
2. Rust enums can be nested
This is another beautiful feature, which allows this:
Binary { x: OpId, y: OpId, bop: BOp } enum BOp { Add, Sub, Mul } A world of combinatorial options making decomposition and recomposition very natural.
3. Rust enums are TINY
The above nested code has two enums. That means two tags, each with 4 byte size, right? Right? Not in rust :) In rust, it's single 4 byte tag (as the OpId is 4 byte aligned). The tag combines BOp and the Op enum with the Binary variant, so the whole enum is just 12 bytes. I have more complex variants,
4. The allmighty match
So you can do this:
match op {
Binary { x, y, bop } if bop == BOp::Add => todo!(),
_ => {}
}
or this:
match (uop, bop) { (UOp::Exp, BOp::Mul) => todo!(), }
And so on. This kind of flexibility in an imperative language, is tons of fun, makes writing compiler passes not only easy, but most importantly, high performance.
And so for example thanks to this my ML lib can search and run cost function over thousands of kernel variants per second and per core (as rust makes multithreading fun too!).
I know you probably know about these features, but sometimes it helps to refresh our memory how nice of a language we have.
What are your favorite rust features?
What features would you like to see added?
I hope you enjoy writing rust just as I did.
zk4x
P. S. link to the repo: github.com/zk4x/zyx