如何 运行 cargo with features flag

How to run cargo with features flag

我正在尝试通过编写 CLI 来学习 Rust,但是我不能 cargo run 具有已通过的功能,我不明白为什么。我阅读了文档/堆栈,但仍然不明白为什么会这样。感觉应该是这样的https://doc.rust-lang.org/cargo/commands/cargo-run.html

我正在尝试 运行 此代码

https://github.com/clap-rs/clap/blob/master/examples/17_yaml.rs

使用命令 cargo run --features=yamlcargo run --features yaml。我尝试了很多组合,其中 none 个有效。

我的 Cargo.toml 看起来像这样:

[dependencies.clap]
version = "*"
default-features = false
features = ["yaml"]

当我 运行 我有错误:

:!cargo run --features=yaml
error: Package `fun v0.1.0 (/Users/XXX/Projekty/rust/fun)` does not have these fe
atures: `yaml`

shell returned 101

我做错了什么?

他们的代码希望您克隆 clap 存储库,更改到它的目录,然后从那里 运行 cargo run --features yaml --example 17_yamlYou can read more about how the cargo examples feature works here.

如果你打算复制他们的代码,如noted in that example code,你必须删除这个条件编译属性:

// Note: If you're using clap as a dependency and don't have a feature for your users called
// "yaml", you'll need to remove the #[cfg(feature = "yaml")] conditional compilation attribute
#[cfg(feature = "yaml")]
fn main() {

否则它将加载 this other main implementation 并发出错误:

#[cfg(not(feature = "yaml"))]
fn main() {
    // As stated above, if clap is not compiled with the YAML feature, it is disabled.
    println!("YAML feature is disabled.");
    println!("Pass --features yaml to cargo when trying this example.");
}

您实际上不需要在命令行上传递 --features 除非您如上所述 运行 在他们的板条箱中安装他们的示例。如果您要复制他们的代码,您还应该删除整个函数!仅当 运行 作为示例时才相关。