Feature use results in lots of Rust Analyzer warnings

When using features, and cfg attributes to control code generation,
my resulting code produces lots of warning on 'cargo check', or in vscode with Rust Analyzer.

Of course those all valid warnings, because with my feature flipped one way or another, there is actually lots of unused imports, etc.

I am just wondering is there a better system or way of dealing with this than disabling unused code warning, and unused import warnings?

This issue gently pushes me back using run-time, not compile-time behavior flags,
because everything lints out so easily and cleanly.

Thanks for any thoughts.

If an import is only needed when some feature is enabled, you should apply #[cfg(feature = "...")] to the import so that it's only present when needed. If you have a lot of such imports, the cfg-if crate will likely be helpful.

3 Likes

Here is how I like to handle conditional imports:

  1. Create entire modules that are conditionally compiled, so that all the uses are inside that scope.

    struct MyStruct {...}
    
    #[cfg(feature = "foo")]
    mod impl_foo {
        use super::*;
        use foolib::{Foo, Foomph};
    
        impl Foo for MyStruct {
            ...
        }
    }
    
  2. For simple cases, just avoid use entirely in favor of full paths:

    struct MyStruct {...}
    
    #[cfg(feature = "foo")]
    impl foolib::Foo for MyStruct {
        ...
    }
    

Both of these will minimize clutter of repeated cfgs. The nested module helps in complex situations like where two different features both require an import (I fixed an actual bug in a library due to that kind of mistake!), because each optional module has its own imports.

3 Likes

Okay, thanks, that makes sense, I'll check out the cfg-if crate also.

Oh wow, yeah, using those two techniques should clean up the linting. Thank you!