Course contentsShow
← Rust
Lesson 3 of 1,9101. Rust Fundamentals and ToolingFree lesson

Managing Dependencies via Cargo.toml

Declare project dependencies and understand how semantic versioning controls your build environment.

In this lesson, you will learn how to add external code libraries to your project and ensure your program stays stable using version control.

What is a Dependency?

In the Rust ecosystem, we don't write every single piece of code from scratch. If you need to perform complex math, connect to a database, or format text, you can use "crates"—libraries written by the community. To use these, you declare them as dependencies in your Cargo.toml file.

Editing Cargo.toml

When you run cargo new, Cargo generates a Cargo.toml file in your project folder. This is the "manifest" for your project. To add a library, you simply list it under the [dependencies] section.

For example, if you wanted to use a popular random number generator called rand, your file would look like this:

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

[dependencies]
rand = "0.8.5"

Once you save this file, Cargo does the heavy lifting: the next time you build your project, it will automatically download that code and integrate it into your build environment.

Semantic Versioning

You’ll notice the number 0.8.5. This follows Semantic Versioning (SemVer).

  • 0 (Major): Breaking changes.
  • 8 (Minor): New features that are compatible with the old ones.
  • 5 (Patch): Bug fixes that don't change how your code works.

By setting the dependency to "0.8.5", you are telling Cargo: "I want to use this specific version, but if a bug-fix version like 0.8.6 comes out, it is safe to use that instead." This keeps your project predictable. If the authors release a major update (like 1.0.0), Cargo will not automatically upgrade your project, because that might contain "breaking changes" that could stop your code from compiling. This protection ensures that your project remains stable, even as the outside world of libraries continues to evolve.

Key Takeaway: The Cargo.toml file serves as the single source of truth for your project’s dependencies, using Semantic Versioning to balance the need for updates with the requirement for long-term build stability.