如果禁用相关功能,如何跳过依赖项

How to skip a dependency if related feature is disabled

假设我有一个板条箱,它仅在 #[cfg(feature = "glob")] 启用时才依赖于 glob 板条箱。此外,默认情况下禁用此功能。如何默认跳过 glob crate 的下载和编译?

# Cargo.toml
...
[features]
default = []

[dependencies]
glob = "0.2"
...

以及源代码:

# lib.rs
.. several uses

#[cfg(feature = "glob")]
extern crate glob;

... a lot of code that doesn't use glob crate.

#[cfg(feature = "glob")]
impl Foo for Bar { 
    // only this code uses glob crate 
}

必须将 glob 依赖项标记为可选:

[dependencies]
glob = { version = "0.2", optional = true }