Conditionally compiling example based on enabled features?

⚓ Rust    📅 2026-05-21    👤 surdeus    👁️ 1      

surdeus

What is a clean way of having examples that depend on optional features not be compiled during a cargo test invocation?

For context: I have a crate with a non-default feature that enables some optional functionality. For this crate, I also have some examples in the examples/ directory, some of which demonstrate use of said optional functionality, but cargo test will automatically compile all examples to help prevent bitrot, including the ones that use the optional functionality. Those examples will fail to compile, obviously causing cargo test to report failures that are simply due to features not being specified.

With integration tests, I typically annotate them with #![cfg(feature = "featuregate")] as the first non-comment line of the file; since they generally use the test driver, an empty file is valid. If I apply this to an example that has a main() function, the then compiler rightfully sees the file as empty and complains about a lack of main(). I know I could wrap everything in an internal module and conditionally-compile the module, but that a) is ugly, b) complicates the examples unnecessarily, and c) feels like it's using a scalpel to solve a problem more suited for a sledgehammer.

(I'm aware of the required-features manifest key, but this does not prevent compilation when the feature is not enabled, merely making the compilation errors more useful.)

Any commentary or solutions would be welcome!

3 posts - 2 participants

Read full topic

🏷️ Rust_feed