Dependencies

crates.io is the Rust community's central package registry that serves as alocation to discover and download packages. cargo is configured to use it bydefault to find requested packages.

To depend on a library hosted on crates.io, add it to your Cargo.toml.

Adding a dependency

If your Cargo.toml doesn't already have a [dependencies] section, add that,then list the crate name and version that you would like to use. This exampleadds a dependency of the time crate:

  1. [dependencies]
  2. time = "0.1.12"

The version string is a semver version requirement. The specifyingdependencies docs have more information aboutthe options you have here.

If we also wanted to add a dependency on the regex crate, we would not needto add [dependencies] for each crate listed. Here's what your wholeCargo.toml file would look like with dependencies on the time and regexcrates:

  1. [package]
  2. name = "hello_world"
  3. version = "0.1.0"
  4. authors = ["Your Name <you@example.com>"]
  5. edition = "2018"
  6. [dependencies]
  7. time = "0.1.12"
  8. regex = "0.1.41"

Re-run cargo build, and Cargo will fetch the new dependencies and all oftheir dependencies, compile them all, and update the Cargo.lock:

  1. $ cargo build
  2. Updating crates.io index
  3. Downloading memchr v0.1.5
  4. Downloading libc v0.1.10
  5. Downloading regex-syntax v0.2.1
  6. Downloading memchr v0.1.5
  7. Downloading aho-corasick v0.3.0
  8. Downloading regex v0.1.41
  9. Compiling memchr v0.1.5
  10. Compiling libc v0.1.10
  11. Compiling regex-syntax v0.2.1
  12. Compiling memchr v0.1.5
  13. Compiling aho-corasick v0.3.0
  14. Compiling regex v0.1.41
  15. Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)

Our Cargo.lock contains the exact information about which revision of all ofthese dependencies we used.

Now, if regex gets updated, we will still build with the same revision untilwe choose to cargo update.

You can now use the regex library in main.rs.

  1. use regex::Regex;
  2. fn main() {
  3.     let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
  4.     println!("Did our date match? {}", re.is_match("2014-01-01"));
  5. }

Running it will show:

  1. $ cargo run
  2. Running `target/hello_world`
  3. Did our date match? true