我正在使用一些 Rust 不稳定的功能,但我仍然希望能够使用稳定的 Rust 编译我的库的简化版本。我很高兴仅在编译器支持时包含那些不稳定的功能,并在不支持时排除它们。
我认为使用条件编译(例如)可以很容易地实现这个目标#[cfg(rust_version = "nightly")],但似乎“稳定”与“每晚”都不是cfg 选项。
你们如何根据“稳定”与“夜间”或基于编译器版本来执行条件编译?
我建议为您的夜间代码创建一个默认禁用的功能,例如
\nCargo.toml
[features]\ndefault = []\nnightly-features = []\nRun Code Online (Sandbox Code Playgroud)\n由于该nightly-features功能不是默认的,因此使用稳定的工具链进行编译可以开箱即用。您可以使用属性 #[cfg(feature = "nightly-features")]并#[cfg(not(feature = "nightly-features"))]在夜间专用版本中包含或排除代码。此方法的另一个好处是允许独立于编译器测试夜间功能(即回答问题:编译器是否破坏了我的代码,或者启用的代码是否包含nightly-features错误?)。
使用构建脚本,有时build.rs除了上述夜间功能之外还会调用。(注意:切勿在库中使用以下内容,否则切换编译器可能会成为重大更改。更喜欢上面解释的解决方案)
build.rs(进入包根目录)
use std::env;\n\nfn main() {\n let rust_toolchain = env::var("RUSTUP_TOOLCHAIN").unwrap();\n if rust_toolchain.starts_with("stable") {\n // do nothing\n } else if rust_toolchain.starts_with("nightly") {\n //enable the \'nightly-features\' feature flag\n println!("cargo:rustc-cfg=feature=\\"nightly-features\\"");\n } else {\n panic!("Unexpected value for rustc toolchain")\n }\n}\n\nRun Code Online (Sandbox Code Playgroud)\n此构建脚本检查rustup设置的工具链环境变量(某些 rust 安装不使用 rustup),并在编译器为夜间编译器时启用夜间功能标志。
\nsrc/main.rs
fn main() {\n #[cfg(feature = "nightly-features")]\n println!("Hello, nightly!");\n #[cfg(not(feature = "nightly-features"))]\n println!("Hello, stable!");\n}\nRun Code Online (Sandbox Code Playgroud)\n现在,跑步
\n\xe2\x9e\x9c cargo +stable run \nHello, stable!\n\xe2\x9e\x9c cargo +nightly run\nHello, nightly!\nRun Code Online (Sandbox Code Playgroud)\n据我所知,没有。cargo +nightly run --no-default-features由于货物如何将标志传递给 rustc,运行会使该功能保持打开状态。程序员可以创建一个特定的环境变量,build.rs 检查该环境变量以跳过自动版本检测,但这比没有构建脚本的替代方案更复杂 -cargo build --features=nightly-features
您可以使用rustversion crate ,而不是建议的解决方案,它的工作方式非常相似(但解析 的输出rustc --version)。
\xe2\x9e\x9c cargo +stable run \nHello, stable!\n\xe2\x9e\x9c cargo +nightly run\nHello, nightly!\nRun Code Online (Sandbox Code Playgroud)\n