How unused code stripping works for Rust?

Hi,

I'm wondering how unused code stripping works for Rust:

I have an error crate which contains an enum MyError and which depends on a lot of other crates (reqwest, tokio, diesel...) to import those crates' errors and impl From those errors.

If a program rely on my error crate, when compiling, will Rust strip all the unused code from those crates (reqwest, tokio, diesel...) because I'm only using their Errors types, or will my executable contains all the code from all those crates?

Are you compiling in Debug mode, which optimizes compile time, or in Release mode, which optimizes the final code?

Release mode.

What I want to do is to use a common error crate for both my client and server, but I'm worried that it will include all my server's dependencies (which are not used) in my client and vice versa.

cargo bloat can help answer this, somewhat. There is also the Godbolt compiler analyzer or just good old objdump if you don't mind getting your hands dirty.

In general, I find that LLVM is pretty good about dead code optimization (yes, it removes code that it can prove is dead). I've seen varying results to the final binary size (release mode) when enabling LTO or thin-LTO specifically because it can help prove that code is dead. Testing different permutations of compiler options would be a useful exercise.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.