Search code examples
rustrust-cargorust-no-std

How to write a crate so that std and no_std can coexist in different modules?


I want to write a library, some modules need to support no_std, and others need to support std.

I tried to write it with reference to other libraries, but it still seems to be wrong.

Cargo.toml:

[features]
default = ["std"]
std = []

lib.rs:

#![cfg_attr(feature = "no_std", no_std)]

#[cfg(feature = "no_std")]
pub mod no_std;

#[cfg(feature = "std")]
pub mod std;

Rust Analyzer told me:

code is inactive due to #[cfg] directives: feature = "no_std" is disabled

How to control the feature in lib.rs correctly?

Moreover, I want to write a model dependent on rayon crate. How can I add it through feature?


Solution

  • #![cfg_attr(not(feature = "std"), no_std)]
    
    #[cfg(not(feature = "std"))]
    pub mod no_std {
        use std::collections::VecDeque;
    }
    
    #[cfg(feature = "std")]
    pub mod with_std {
        use std::collections::VecDeque;
    
    }
    
    [features]
    default = ["std"]
    std = []
    
    
    $ cargo c
    warning: unused import: `std::collections::VecDeque`
      --> src\lib.rs:10:9
       |
    10 |     use std::collections::VecDeque;
       |         ^^^^^^^^^^^^^^^^^^^^^^^^^^
       |
       = note: `#[warn(unused_imports)]` on by default
    
    warning: `draft1` (lib) generated 1 warning
        Finished dev [unoptimized + debuginfo] target(s) in 0.00s
    
    $ cargo c --no-default-features
        Checking draft1 v0.1.0 (draft1)
    error[E0433]: failed to resolve: use of undeclared crate or module `std`
     --> src\lib.rs:5:9
      |
    5 |     use std::collections::VecDeque;
      |         ^^^ use of undeclared crate or module `std`
    
    For more information about this error, try `rustc --explain E0433`.
    error: could not compile `draft1` due to previous error