Search code examples
dependenciesrustconditional-compilationrust-cargorust-crates

How to skip a dependency if related feature is disabled


Suppose I have a crate which depends on the glob crate only if #[cfg(feature = "glob")] is enabled. Also, this feature is disabled by default. How can I skip downloading and compiling of the glob crate by default?

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

[dependencies]
glob = "0.2"
...

And the source code:

# 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 
}

Solution

  • The glob dependency must be marked as optional:

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