Hacker News new | ask | show | jobs
by josephg 2 days ago
> Until Rust has equal meta-programming support to C++ it's always going to be "slower".

What metaprogramming does C++ have that rust is lacking?

If you need more than traits + generics, rust also has proc macros. Proc macros are essentially portable compiler extensions. They take in a stream of symbols from the user's program at compile time and emit rust code that gets passed straight to the compiler. You lose out on syntax highlighting and they make compilation slower. But macros are essentially compile-time code gen. They work great. In rust, you can do things like JSX at compile-time without any special compiler support. (See: leptos.)

> Realistically the difference doesn't matter much and if you're writing code that must be as fast as possible your writing unsafe Rust that looks a lot more like C/C++ then anything Rust.

I agree that the difference is small in practice. Good rust often does look a lot like C - with plain structs everywhere and lots of global-ish scoped functions.

But I don't agree about unsafe. I've spent some time porting well optimised code from C to rust. I generally find I need far less unsafe code than I expected. I ported a ~500 line skip list implementation from C to rust a few years ago. I think my rust code ended up using just 2 unsafe functions. The rest of the code didn't need any unsafe at all.

My skip list was a monster to debug in C because most logic bugs ended up corrupting memory. As a result, a bug in one function caused crashes in far away code. In rust, debugging was much easier. There wasn't any "spooky action at a distance". And that let me reason about the code much more easily. As a result, once I got it working I ended up adding a few more optimisations in rust that I was too overwhelmed to write in C. The rust code is now ~2-3x faster.

If you're interested:

https://github.com/josephg/jumprope-rs#benchmarks

C code is here: https://github.com/josephg/librope

1 comments

> What metaprogramming does C++ have that rust is lacking?

Compile time execution, and compile time reflection, with the same syntax.

Proc macros are still a kludge having to depend on syn crate, and some stuff used to depend on nightly, is that still the case, I don't keep track?

Additionally type specialisation, and explicit templates.

Proc macros haven't depended on nightly things in a very, very very long time.
Thanks for the update, outside some weekend experiments, or having to compile from source some specific tools, I don't have much reasons to write Rust, thus not keeping that much other than conference talks that pop up on my feeds.