4

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?

Flavio Vilante
  • 5,131
  • 1
  • 11
  • 15
hzqelf
  • 857
  • 7
  • 17
  • 6
    _if you want to optionally support no_std environments, do not use a no_std feature. Instead, use a std feature that enables std_ ([Reference](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification)). `#![no_std]` doesn't prevent linking std, you can link `std` manually as example shows in the reference – Ömer Erden Sep 29 '21 at 15:13

1 Answers1

2
#![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

whfuyn
  • 153
  • 5
  • Have you tried this code? I copied and pasted it, `no_std` shows ```code is inactive due to #[cfg] directives: feature = "std" is enabled```, and `with_std` shows ```code is inactive due to #[cfg] directives: features = "std" is disabled``` – hzqelf Sep 29 '21 at 16:29
  • @hzqelf Yes, I tried it. It works as expected. rust-analyzer's output is wrong. – whfuyn Sep 29 '21 at 17:14
  • @hzqelf Sorry, I made some mistakes, now fixed. – whfuyn Sep 29 '21 at 17:39