我可以根据平台设置 Cargo 项目的默认功能吗?

Tim*_*sée 13 rust rust-cargo

default 是否可以使功能列表依赖于您的平台Cargo.toml?我想使用功能来选择依赖于平台的依赖项。

我会想象这样的事情:

[features]
# on Unix
default = ["feature-a"]
# not on Unix
default = ["feature-b"]

feature-a = ["dep-a"]
feature-b = ["dep-b"]

[dependencies]
dep-a = { version = "*", optional = true }
dep-b = { version = "*", optional = true }
Run Code Online (Sandbox Code Playgroud)

我试过了:

  • 使用[target.'cfg(unix)'.features]不起作用,它被忽略:

    [target.'cfg(unix)'.features]
    default = ["feature-a"]
    # -- snip --
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用build.rs脚本根据cfg条件启用功能只能部分起作用。依赖关系解析是在运行之前完成的build.rs,因此这不会导入其中启用的功能的可选依赖关系。此示例不会导入dep-a

    fn main() {
        #[cfg(unix)]
        println!("cargo:rustc-cfg=feature=\"feature-a\"");
        // -- snip --
    }
    
    Run Code Online (Sandbox Code Playgroud)

这可以在 Rust 本身内实现,而不需要外部脚本吗?

wan*_*len 0

您可以features在每个下指定不同的cfg。不支持cfgroot 部分features。这样您就可以以不同的方式实现您的目标。

您可以对不同的功能集有不同的依赖关系。

例如:

[target.'cfg( target_os = "android" )'.dependencies]
some_dep = { version = "0.3.0", features = [ "feature1" ] }

[target.'cfg( target_os = "ios" )'.dependencies]
some_dep = { version = "0.3.0", features = [ "feature2" ] }
Run Code Online (Sandbox Code Playgroud)

官方文档

  • 这并没有达到同样的目标。通过这种方法,最终用户无法使用“--no-default-features”和“--features”来管理使用的功能。这就是为什么我明确指出要使“默认”设置依赖于平台,而不是根据当前平台选择依赖项功能。 (7认同)
  • 这与在不同平台上拥有一组不同的“默认”功能不同。 (4认同)