Dependencies

Use Items from External Crates (Dependencies) in your Code

To use a (public) item (structs, enums, traits, functions, etc.) of an external crate, first make sure to include the external crate as a dependency in your crate's Cargo.toml file, for example:

[dependencies]
anyhow = "1.0.95"

The name of the external crate is followed by = and a semantic version specifier. See the Cargo chapters for details.

You can then refer to its items using a path that starts with the external crate's name:

// Returns a `Result` from the `anyhow` crate:
fn a_func() -> anyhow::Result<()> {
    Ok(())
}

The path may include one or more modules as needed e.g., <crate_name>::<module_name>::<item_name>.

You may start the path with :: followed by the name of the crate, if a crate name is the same than a module in your crate.

Once you add an external crate as a dependency, you will very often bring items from external crates into scope with the use keyword. See the use Keyword chapter for details.

// Bring the following items into scope:
use anyhow::Result; // A type alias.
use anyhow::anyhow; // The `anyhow!` macro.
use anyhow::Error;  // A struct.

// Refer to `Result` without having to write its full path every time:
fn main() -> Result<()> {
  // ...
  Ok(())
}

References