Cargo.toml

Cargo.toml is one of the boilerplate files generated by cargo new. This is where we manage dependencies and other configurations. The starter file is quite simple.

[package]
name = "grep"
version = "0.1.0"
edition = "2021"

[dependencies]

Adding a Dependency

Adding dependencies is as simple as specifying the name of the crate and the desired version1 in the [dependencies] section of the Cargo.toml file. Here's how we add the regex crate.

regex = "1.11.1"

We can also use cargo add:

$ cargo add regex
    Updating crates.io index
      Adding regex v1.11.1 to dependencies
             Features:
             + perf
             + perf-backtrack
             + perf-cache
             + perf-dfa
             + perf-inline
             + perf-literal
             + perf-onepass
             + std
             + unicode
             + unicode-age
             + unicode-bool
             + unicode-case
             + unicode-gencat
             + unicode-perl
             + unicode-script
             + unicode-segment
             - logging
             - pattern
             - perf-dfa-full
             - unstable
             - use_std
    Updating crates.io index
     Locking 5 packages to latest compatible versions
      Adding aho-corasick v1.1.3
      Adding memchr v2.7.4
      Adding regex v1.11.1
      Adding regex-automata v0.4.9
      Adding regex-syntax v0.8.5

Either method produces the same result.

[package]
name = "grep"
version = "0.1.0"
edition = "2021"

[dependencies]
regex = "1.11.1"

Exercise

These exercises must be completed locally.

  • Add the clap crate and include the derive2 feature. More information to accomplish this can be found here and here.
Solution
clap = { version = "4.5.21", features = ["derive"] }
regex = "1.11.1"
1

Semantic version numbers (i.e. SemVer) are supported. Refer to the documentation on specifying dependencies for more advanced version control.

2

Features of dependencies can be enabled within the dependency declaration. The features key indicates which features to enable. The Cargo Book covers this under the Dependency features section.