1

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

我尝试参考其他库来编写它,但它似乎仍然是错误的。

货物.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 告诉我:

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

如何正确控制featurein lib.rs

此外,我想写一个依赖于rayoncrate 的模型。我怎样才能通过添加它feature

4

1 回答 1

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

于 2021-09-29T15:53:02.267 回答