Here are the typical commands to build and run a Rust program, along with explanations and examples:
1. Create a New Rust Project
sh
cargo new my_project
- Creates a new directory
my_project with:
src/main.rs (entry point for binaries)
Cargo.toml (project manifest/dependencies)
- For a library (instead of a binary):
sh
cargo new --lib my_lib
2. Build the Project
- Compiles the project in debug mode (unoptimized, with debug symbols).
- Outputs to
./target/debug/my_project (or my_lib for libraries).
Build in Release Mode (Optimized)
sh
cargo build --release
- Optimizes the binary for performance (slower compile time).
- Outputs to
./target/release/my_project.
3. Run the Project
- Compiles (if needed) and runs the program in debug mode.
- Equivalent to:
sh
cargo build && ./target/debug/my_project
Run in Release Mode
sh
cargo run --release
- Runs the optimized release binary.
4. Check for Compilation Errors (Without Building)
- Quickly checks syntax and types without generating an executable.
- Faster than
cargo build for iterative development.
5. Run Tests
- Runs all unit tests, integration tests, and doc-tests in the project.
6. Generate Documentation
sh
cargo doc --open
- Generates HTML documentation for your project and dependencies.
- Opens the docs in your default browser.
7. Clean Build Artifacts
- Deletes the
target/ directory to free up space.
8. Add Dependencies
Edit Cargo.toml and add your dependencies:
toml
[dependencies]
serde = "1.0" # Example: Adds the `serde` crate
Then run:
- Downloads and compiles dependencies.
9. Run a Specific Binary (Workspace or Multiple Bins)
If your project has multiple binaries (e.g., src/bin/extra.rs):
sh
cargo run --bin extra
10. Cross-Compile for Another Platform
Install the target (e.g., for ARM):
sh
rustup target add arm-unknown-linux-gnueabihf
Then build:
sh
cargo build --target=arm-unknown-linux-gnueabihf
Example Workflow
- Create a new project:
sh
cargo new hello_world
cd hello_world
- Edit
src/main.rs:
rust
fn main() {
println!("Hello, Rust!");
}
- Run it:
Output:
code
Hello, Rust!
Key Takeaways
cargo new: Create a project.
cargo build: Compile (debug mode).
cargo run: Compile + run.
cargo check: Fast syntax check.
cargo test: Run tests.
--release: Optimized builds.
These commands cover 95% of Rust development workflows. For more, check cargo --help or The Cargo Book.