This roadmap follows The Rust Programming Language and the official Rust docs to guide you step-by-step through Rust concepts with examples.
- Getting Started
- Common Programming Concepts
- Understanding Ownership
- Structs
- Enums & Pattern Matching
- Modules & Packages
- Collections
- Error Handling
- Generics
- Traits & Lifetimes
- Testing
- Advanced Topics
Install Rust using the official installer:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
### Your First Program
Create a new project:
```bash
cargo new hello_world
cd hello_world
Edit src/main.rs:
fn main() { println!("Hello, world!"); }
Build and run:
cargo run
let x = 5; println!("x = {}", x); let mut y = 10; y = 20; println!("y = {}", y);
const MAX_POINTS: u32 = 100_000; println!("Max points: {}", MAX_POINTS);
let x = 5; let x = x + 1; let x = x * 2; println!("x = {}", x); // 12
let a: i32 = -10; let b: u32 = 10; let c: f64 = 3.14; let d: char = 'z'; let e: bool = true;
let tup: (i32, f64, u8) = (500, 6.4, 1); let (x, y, z) = tup; let arr = [1, 2, 3, 4, 5];
fn add(a: i32, b: i32) -> i32 { a + b } println!("3 + 4 = {}", add(3, 4));
// This is a comment /* This is a multi-line comment */
let number = 7; if number < 5 { println!("less than five"); } else { println!("five or more"); } for i in 1..4 { println!("i = {}", i); } let mut count = 0; while count < 3 { println!("count = {}", count); count += 1; }
- Each value in Rust has a variable thatβs its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
Example:
{ let s = String::from("hello"); println!("{}", s); } // s is dropped here
References allow you to refer to some value without taking ownership.
Example:
let s1 = String::from("hello"); let len = calculate_length(&s1); fn calculate_length(s: &String) -> usize { s.len() } println!("Length: {}", len);
Mutable references allow you to change the value you borrow.
Example:
let mut s = String::from("hello"); change(&mut s); fn change(some_string: &mut String) { some_string.push_str(", world"); } println!("{}", s);
Rust prevents dangling references at compile time.
Example (will not compile):
// let reference_to_nothing = dangle(); // fn dangle() -> &String { // let s = String::from("hello"); // &s // }
Slices let you reference a contiguous sequence of elements in a collection.
Example:
let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..]; println!("{} {}", hello, world);