Skip to main content

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 name
  • version → project version
  • dependencies → 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);
}
CodeMeaning
fnDefines a function
main()Program entry point
letDeclares 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

CommandPurpose
cargo newCreate new project
cargo runBuild + run
cargo buildCompile
cargo checkCheck errors (fast)
cargo testRun tests
cargo updateUpdate dependencies