← Back to Rust Course | Chapter 1: Setup & Basics | Lesson 5 of 7

Cargo Run and Build

cargo build and cargo run are simple commands that turn your Rust code into a program and, if you want, run it right away.

Building a Project

cargo build compiles your project without running it. The resulting debug executable is placed in target/debug/, and by default this build includes debug information and skips heavy optimizations so compilation itself is fast.

Example: Building a Project

bash
cargo build

⚠️ Run this command in your terminal.

Running a Project

cargo run is a convenience command that compiles your project (only if source files changed) and then immediately executes the resulting binary. This is the command you will use most often while developing.

Example: Running a Project

bash
cargo run

⚠️ Run this command in your terminal.

Release Builds

Passing --release tells Cargo to apply compiler optimizations, producing a smaller and much faster binary at the cost of longer compile times. Release builds are what you ship to production or use for performance benchmarking.

Example: Release Builds

bash
cargo build --release

⚠️ Run this command in your terminal.

Seeing the Output in Code

Whether built in debug or release mode, the program's logic and output are identical -- only speed and binary size differ. This example is exactly what cargo run would execute after scaffolding a project.

Example: Seeing the Output in Code

markup
fn main() {
    println!("Built with cargo build, or run directly with cargo run");
}
Common Mistakes
  1. Running cargo build and then manually hunting for the binary instead of just using cargo run for quick iteration.
  2. Not realizing cargo build --release produces a much faster, optimized binary, and benchmarking with a debug build instead.
  3. Deleting the target/ folder thinking it contains source code, when it is safe-to-delete build output.
Chapter Summary
  • cargo build compiles the project and places the executable under target/debug/.
  • cargo run compiles (if needed) and immediately runs the resulting binary in one step.
  • cargo build --release produces an optimized binary under target/release/, used for production/performance.
  • Cargo only recompiles files that changed, making repeated builds fast.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.