Rust: split header vs impl

Followup to Rust compile times and dependency graphs - #6 by zeroexcuses

In C/C++, there is often this separation of .h / .c, .hpp / .cpp .

In Rust, is it possible to split this into two separate traits?

foo_header // contains structs / enums / traits
foo_impl // contains all the impl blocks

Intuition says no, due to the orphan rules.

The reason why this would be nice is the ability for potentially faster compilation, where a crate can depend on foo_header w/o depending on foo_impl (and get passed an Rc<dyn ...> at runtime).

Oh boy, for so many decades I have loathed header files and prayed for the day I could use a language that did not have them. Rust was a gift from the Gods just for that! Now people want them back again!

Oddly in the C++ world there is what seems to be an increasing trend to want to put code into header files.Mostly because the compiler cannot inline functions/methods it cannot see because it only has the header.

I also see a trend to "header only libraries" mostly because it is much simpler and avoids any build system problems, I think.


Yes. That is NOT the direction I am going in. I am not a big fan of tempplate-meta-programming errors.

I am willing to pay the runtime cost of a Rc<dyn ...> in certain situations for faster builds.

Hmmm. A quick

rg 'struct|impl'

in the Materialize sources looks like they have their impl blocks in the same files as their struct definitions. Just like we would expect.

Cargo pipelined compilation (available since Rust 1.38) already provides some of these benefits by starting to compile dependent crates before the dependency is fully compiled. It doesn't allow completly compiling them in parallel (the metadata of the dependency still needs to be available before the dependent can start compiling), but it's still a big improvement.

You can already do this if you define the Trait of the Rc<dyn Trait> in foo_header and then implement it somewhere else.

1 Like

And the frontend parallelization effort should lead to the metadata becoming available earlier during compilation.

1 Like

I spent the past few hours doing Rc<dyn T> kungfu to reduce crate dependency and reduce expanding generics ... and I think I somehow managed to increase my incremental compile time. :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.