Search code examples
rustrust-cargoconditional-compilation

Use only one feature flag attribute with multiple use statements in Rust


Is it possible to use only one feature flag attribute for multiple use statements in Rust? Something like this:

#[cfg(feature = "my-flag")]
{
  use crypto::sha2::Sha256;
  use ethers::utils::keccak256;
}

Note: The compiler throws a Syntax Error for the above.

Currently I have to use one flag attribute for each use statement like this:

#[cfg(feature = "my-flag")]
use crypto::sha2::Sha256;
#[cfg(feature = "my-flag")]
use ethers::utils::keccak256;

Can this be shortened?


Solution

  • You can use cfg-if:

    cfg_if::cfg_if! {
        if #[cfg(feature = "my-flag")] {
            use crypto::sha2::Sha256;
            use ethers::utils::keccak256;
        }
    }