What are the benefits of using crate as translation unit instead of a source file?


#1

I am burning of curiosity, what are the benefits of using crate as translation unit instead of a source file (C/C++) ?


#2

I think it makes it easier for the compiler to do optimisations across modules (but within the same crate), to do that with C/C++ you need LTO and that’s not normally on by default.

Another thing is you don’t get cyclic import errors, e.g. I put my error type in lib.rs, then foo.rs uses the error, while lib.rs imports something from foo.rs so it can be exported as part of the public API. Also, because the Rust compiler isn’t a single-pass compiler (which usually goes hand in hand with source file translation units) you don’t have to declare everything before you can use it.

They’re some of the reasons I can think of off the top of my head anyway. I’ve played around with compilers for you languages before, but I’m sure the guys on the compiler team would be able to tell you more or correct me if I’m wrong.


#3

It also means that, if a crate uses a particular generic instance (like Vec<MyTy>) all over the place, it will only be monomorphised once for the crate, instead of once for every source file.

Admittedly, this improves the worst-case performance (time spent compiling from scratch) but probably makes the best-case performance (time spent if the compiler only needs to do a part of a crate) worse.