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

我想写一个库,有的模块需要支持 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 Analyzer told me:**

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

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

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

stack overflow How to write a crate so that std and no_std can coexist in different modules?
原文答案
author avatar

接受的答案

#![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`
  --> srclib.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`
 --> srclib.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

答案: