如何编写一个 crate 以便 std 和 no_std 可以在不同的模块中共存?

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

我想写一个库,有的模块需要支持no_std,有的模块需要支持std

我试过参考其他库写的,但是好像还是不对

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 分析器告诉我:

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

如何正确控制lib.rs中的feature

此外,我想写一个依赖于rayon crate 的模型。如何通过feature添加?

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