First Project
Cargo makes Rust development easy.
Create a project
cargo new hello_rust
f This creates:
hello_rust/
├── Cargo.toml
└── src/
└── main.rs
Understand the Files
Cargo.toml (Project configuration)
[package]
name = "hello_rust"
version = "0.1.0"
edition = "2021"
[dependencies]
name→ project nameversion→ project versiondependencies→ external libraries
src/main.rs (Main program)
fn main() {
println!("Hello, Rust!");
}
Running the Program
Inside the project folder:
cd hello_rust
cargo run
Output:
Hello, Rust!
Your first Rust program is running!
Explanation of the Example Code
fn main() {
let name = "Rust";
println!("Hello, {}!", name);
}
| Code | Meaning |
|---|---|
fn | Defines a function |
main() | Program entry point |
let | Declares a variable |
"Rust" | String literal |
{} | Placeholder for formatting |
println! | Macro to print text to the console |
! | Indicates a macro (not a normal function) |
Building Without Running
To compile only:
cargo build
To build an optimized version:
cargo build --release
Compiled files go to:
target/
├── debug/
└── release/
Adding a Dependency Example
Let’s add a dependency to show Cargo’s power.
Step 1: Edit Cargo.toml
[dependencies]
rand = "0.8"
Step 2: Use it in code
use rand::Rng;
fn main() {
let number = rand::thread_rng().gen_range(1..=10);
println!("Random number: {}", number);
}
Step 3: Run
cargo run
Cargo will:
- Download
rand - Compile it with
rustc - Link it automatically
Useful Cargo Commands
| Command | Purpose |
|---|---|
cargo new | Create new project |
cargo run | Build + run |
cargo build | Compile |
cargo check | Check errors (fast) |
cargo test | Run tests |
cargo update | Update dependencies |