What Is the Difference Between cargo build and cargo run?

`cargo build` compiles your project and places the executable in the `target/debug` directory without executing it, while `cargo run` performs the compilation step (skipping it if the binary is already up to date) and immediately launches the resulting executable.

cargo build compiles your project and places the executable in the target/debug directory without executing it, while cargo run performs the compilation step (skipping it if the binary is already up to date) and immediately launches the resulting executable. Use build when you need the binary file for deployment, testing, or manual execution, and use run for quick development iterations where you just want to see the program's output.

Here is a practical example showing the difference in workflow:

# Compiles the project but does not execute it
# Output: Compiling my_project v0.1.0 (file:///path/to/project)
#         Finished dev [unoptimized + debuginfo] target(s) in 1.2s
cargo build

# The binary now exists at target/debug/my_project
# You can verify it exists without running it
ls -lh target/debug/my_project

# Compiles (if needed) and immediately runs the binary
# Output: Compiling my_project v0.1.0 ... (skipped if unchanged)
#         Finished dev [unoptimized + debuginfo] target(s) in 0.0s
#         Running `target/debug/my_project`
#         Hello, world!
cargo run

If you need to pass arguments to your program, cargo run handles them cleanly by appending them after --. For example, cargo run -- --verbose passes --verbose to your binary. If you used cargo build, you would have to manually construct the path to the binary in your shell: ./target/debug/my_project --verbose.

A common pitfall is assuming cargo build runs your tests or checks for runtime errors; it only checks for compile-time errors. If your code compiles successfully but crashes at runtime due to a panic or logic error, cargo build will report success, whereas cargo run will immediately show you the crash stack trace. This makes cargo run the superior choice for the "edit-compile-run" loop during active development, while cargo build is essential when you need to inspect the binary size, move the artifact to another machine, or integrate it into a larger build pipeline that separates compilation from execution.