Using Cargo to Build, Check, or Run our Project

Learn how to build and execute projects in Rust.

We’ve now become familiar with Cargo. Cargo offers a few other ways to interact with our program. We can type cargo help for a full list or cargo [command] --help for detailed help about a command’s options. We can:

  • Quickly check to see if a project is valid by typing cargo check. This checks our project and its dependencies for basic structural errors, typically much faster than a full build.

  • Compile without running our project with cargo build.

  • Remove the entire target directory (into which compiled code is placed) with cargo clean.

Cargo provides a few options to customize our build setup.

Debug and release builds

When we execute cargo run or cargo build, our project is built in debug mode. It contains very few optimizations, making it run much more slowly than it could. This makes it easier to debug and for Rust to tell us exactly what went wrong, but our program may run more slowly.

It also emits debug information, which is data our debugging tool can read to associate errors with lines of code. This makes for a much larger compiled program.

We can compile and run our program in release mode with the command, cargo run --release. The compiler applies optimizations without using extra space to provide debugger support.

We get a much faster and smaller program, but it’s much harder to fix. When it comes time to release our program, compile it in release mode.

Formatting our code

When we’re sharing our code with others, it’s helpful to have a standardized layout for our code. Rust provides a style guide, but it can be difficult to remember, so Rust includes a formatter that can help us adhere to the standard. The command, cargo fmt, will reformat our code to follow the Rust style guide.

Suppose we’re in a hurry and write “Hello, World!” as a one-line program. This program will compile and run, but it’s very different from the standard. If we were to share it with our coworkers or as part of an open-source project, we would likely receive comments on the formatting. We can run cargo fmt to transform the terse code back into the recommended format.

When we run cargo fmt, it formats our entire project, and we can then check the formatted file by using cat main.rs. It’s recommended to run it regularly while we work, keeping our project’s formatting consistent. If we dislike its formatting, it has many configuration options.

The formatted result is shown after the command, cat main.rs, in the terminal and looks much better:

Get hands-on with 1200+ tech skills courses.