» Quick Introduction to Rust » 2. Advanced » 2.2 Cargo

Cargo

cargo is the official Rust package management tool.

Dependencies

cargo can manage dependencies for a project.

To create a new Rust project.

# A binary
$ cargo new foo

# A library
$ cargo new --lib bar

After that, you should see a file hierarchy like this:

.
├── bar
│   ├── Cargo.toml
│   └── src
│       └── lib.rs
└── foo
    ├── Cargo.toml
    └── src
        └── main.rs

The main.rs is the root source file for your project. The Cargo.toml is the config file for cargo for this project.

It looks like this:

[package]
name = "foo"
version = "0.1.0"
authors = ["you"]

[dependencies]

Tests

Tests are Rust functions that verify that the non-test code is functioning in the expected manner.

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle {
            width: 8,
            height: 7,
        };
        let smaller = Rectangle {
            width: 5,
            height: 1,
        };

        assert!(larger.can_hold(&smaller));
    }
}

Then, run cargo test to see if it passes.

$ cargo test
   Compiling rectangle v0.1.0
    Finished test [unoptimized + debuginfo] target(s) in 0.51s
     Running unittests src/lib.rs (...)

running 1 test
test tests::larger_can_hold_smaller ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests rectangle

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s