Cargo Dependency Management in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, the concept of development dependencies is explained. Development dependencies are added in the [dev-dependencies] section of the Cargo.toml file and are used for tests, examples, or benchmarks. An example of a development dependency is pretty_assertions, which extends standard macros like assert_eq! and assert_ne! to provide colorful diffs.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/integer_types -.-> lab-99284{{"`Cargo Dependency Management in Rust`"}} rust/function_syntax -.-> lab-99284{{"`Cargo Dependency Management in Rust`"}} rust/expressions_statements -.-> lab-99284{{"`Cargo Dependency Management in Rust`"}} rust/operator_overloading -.-> lab-99284{{"`Cargo Dependency Management in Rust`"}} end

Development dependencies

Sometimes there is a need to have dependencies for tests (or examples, or benchmarks) only. Such dependencies are added to Cargo.toml in the [dev-dependencies] section. These dependencies are not propagated to other packages which depend on this package.

One such example is pretty_assertions, which extends standard assert_eq! and assert_ne! macros, to provide colorful diff.
File Cargo.toml:

## standard crate data is left out
[dev-dependencies]
pretty_assertions = "1"

File src/lib.rs:

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq; // crate for test-only use. Cannot be used in non-test code.

    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
}

Summary

Congratulations! You have completed the Development Dependencies lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like