Rust Documentation
Memory safety without a garbage collector — systems programming that is fast and fearless.
Rust is a compiled systems language that gives you C/C++-level speed and memory safety — without a garbage collector. Its compiler checks ownership and borrowing rules so whole classes of bugs (null pointers, use-after-free, data races) cannot compile. It's used in browsers (Firefox), operating systems, CLI tools, WebAssembly and blockchain.
1. Introduction & Installation
Install with rustup from rustup.rs (on Windows, also install the Visual Studio C++ Build Tools when asked). You get rustc (compiler) and cargo (build tool + package manager).
rustc --version
cargo new hello # creates hello/Cargo.toml and hello/src/main.rs
cd hello
cargo run # build + run
cargo build --release # optimised binary in target/release
fn main() {
println!("Hello, Codify!");
}
Output:
Hello, Codify!
cargo check type-checks fast, cargo fmt formats, cargo clippy gives lint suggestions, cargo add serde adds a dependency (crate).
⚠️ Common error:
linker 'link.exe' not foundon Windows — install the "Desktop development with C++" build tools, or use the GNU toolchain (rustup default stable-x86_64-pc-windows-gnu).
2. Basic Syntax
fn main()is the entry point; statements end with;.println!has a!because it's a macro.{}prints a value,{:?}prints debug output.- The last expression of a block (without
;) is its value — so functions often don't needreturn.
fn square(x: i32) -> i32 {
x * x // no semicolon: this is the return value
}
fn main() {
let name = "Rustacean";
let n = square(7);
println!("Hi {name}, 7 squared is {n}");
println!("{:?} {:>5}|{:<5}|{:.3}", vec![1, 2], 42, "ab", 3.14159);
}
Output:
Hi Rustacean, 7 squared is 49
[1, 2] 42|ab |3.142
⚠️ Common error:
mismatched types: expected i32, found ()— you added a;after the last expression, so the function returns()(nothing).
3. Variables & Data Types
Variables are immutable by default. Add mut to allow changes. Shadowing (let x = ... again) creates a new variable.
| Type | Examples |
|---|---|
| integers | i8 i16 i32 i64 i128 isize, u8 ... u64 usize |
| floats | f32, f64 (default) |
bool, char |
true, 'R' (4-byte Unicode) |
| tuple | (i32, f64, char) |
| array | [i32; 3] (fixed length) |
| strings | &str (borrowed slice), String (owned, growable) |
fn main() {
let x = 5;
let mut count = 0;
count += 1;
let x = x * 2; // shadowing
let big: i64 = 9_000_000_000;
let pi: f64 = 3.14159;
let ok = true;
let letter = 'R';
let point: (i32, i32) = (3, 4);
let arr = [10, 20, 30];
let s: &str = "slice";
let owned: String = String::from("owned");
println!("{x} {count} {big} {pi} {ok} {letter}");
println!("{} {} {} {} {}", point.0, arr[2], arr.len(), s, owned);
println!("{} {} {}", 7 / 2, 7.0 / 2.0, (7 as f64) / 2.0);
println!("{}", "42".parse::<i32>().unwrap() + 1);
}
Output:
10 1 9000000000 3.14159 true R
3 30 3 slice owned
3 3.5 3.5
43
⚠️ Common error:
cannot assign twice to immutable variable— declare it withlet mut.
4. Operators
Arithmetic + - * / %, comparison == != < > <= >=, logical && || !, bitwise & | ^ ! << >>, compound assignment += -= ..., range .. and ..=, and ? for error propagation. There is no ++.
fn main() {
let (a, b) = (17, 5);
println!("{} {} {}", a / b, a % b, -17 / 5);
println!("{} {}", a > b && b > 0, !(a == 17));
println!("{} {} {} {}", 6 & 3, 6 | 3, 6 ^ 3, 1 << 10);
let x: u8 = 250;
println!("{:?} {} {}", x.checked_add(10), x.wrapping_add(10), x.saturating_add(10));
}
Output:
3 2 -3
true false
2 7 5 1024
None 4 255
⚠️ Common error: integer overflow panics in debug builds (
attempt to add with overflow). Use a bigger type orchecked_/wrapping_/saturating_methods.
5. Conditional Statements
if is an expression (it returns a value). match must cover every possible case.
fn main() {
let marks = 82;
let grade = if marks >= 90 { "A" } else if marks >= 75 { "B" } else { "C" };
println!("grade {grade}");
let n = 7;
let kind = match n {
0 => "zero",
1..=9 => "single digit",
10 | 20 | 30 => "round",
_ => "big", // _ matches everything else
};
println!("{n} is {kind}");
let pair = (0, -3);
match pair {
(0, y) => println!("on the y-axis at {y}"),
(x, 0) => println!("on the x-axis at {x}"),
_ => println!("somewhere else"),
}
}
Output:
grade B
7 is single digit
on the y-axis at -3
⚠️ Common error:
non-exhaustive patterns— add the missing cases or a_ =>arm.
6. Loops
fn main() {
for i in 1..=5 { // inclusive range
print!("{i} ");
}
println!();
let langs = vec!["rust", "go", "c"];
for (i, l) in langs.iter().enumerate() {
println!("{i}: {l}");
}
let mut n = 1;
while n < 100 {
n *= 3;
}
println!("n = {n}");
let mut tries = 0;
let found = loop { // loop can return a value with break
tries += 1;
if tries * tries > 50 {
break tries;
}
};
println!("first square > 50 is {found}^2");
for x in (1..10).step_by(3).rev() {
print!("{x} ");
}
println!();
}
Output:
1 2 3 4 5
0: rust
1: go
2: c
n = 243
first square > 50 is 8^2
7 4 1
⚠️ Common error:
for x in vmovesvinto the loop so you can't use it afterwards. Loop over&v(orv.iter()) to borrow it.
7. Functions
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn min_max(v: &[i32]) -> (i32, i32) { // return a tuple
let mut lo = v[0];
let mut hi = v[0];
for &x in v {
if x < lo { lo = x; }
if x > hi { hi = x; }
}
(lo, hi)
}
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { // takes a closure
f(x)
}
fn fib(n: u64) -> u64 {
if n < 2 { n } else { fib(n - 1) + fib(n - 2) }
}
fn main() {
let (lo, hi) = min_max(&[4, -2, 9, 3]);
let offset = 10;
let add_offset = |x| x + offset; // closure captures `offset`
println!("{} {} {} {} {}", add(2, 3), lo, hi, apply(add_offset, 5), fib(20));
}
Output:
5 -2 9 15 6765
⚠️ Common error: parameter types are required in function signatures (unlike closures).
fn add(a, b)does not compile.
8. Arrays & Data Structures
use std::collections::{HashMap, HashSet, VecDeque, BTreeMap, BinaryHeap};
fn main() {
let mut v = vec![5, 2, 8]; // Vec<i32>: growable array
v.push(1);
v.sort();
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();
let evens: Vec<&i32> = v.iter().filter(|x| *x % 2 == 0).collect();
println!("{:?} {:?} {:?} sum={}", v, doubled, evens, v.iter().sum::<i32>());
println!("{:?} {:?}", v.first(), v.get(10)); // safe access returns Option
let mut s = String::from("hello");
s.push_str(" world");
let words: Vec<&str> = s.split(' ').collect();
println!("{} {} {:?} {}", s.len(), s.to_uppercase(), words, &s[0..4]);
let mut freq: HashMap<char, i32> = HashMap::new();
for c in "banana".chars() {
*freq.entry(c).or_insert(0) += 1;
}
let sorted: BTreeMap<_, _> = freq.into_iter().collect(); // sorted by key
println!("{:?}", sorted);
let set: HashSet<i32> = [1, 2, 2, 3].into_iter().collect();
let mut q = VecDeque::from(vec![1, 2]);
q.push_front(0);
let mut heap = BinaryHeap::from(vec![3, 9, 4]);
println!("{} {:?} {:?}", set.len(), q.pop_front(), heap.pop());
}
Output:
[1, 2, 5, 8] [2, 4, 10, 16] [2, 8] sum=16
Some(1) None
11 HELLO WORLD ["hello", "world"] hell
{'a': 3, 'b': 1, 'n': 2}
3 Some(0) Some(9)
⚠️ Common error:
v[10]on a short vector panics (index out of bounds). Usev.get(10), which returnsNone.
9. Object-Oriented Programming
Rust has no classes or inheritance. It uses structs and enums for data, impl blocks for methods, and traits for shared behaviour (polymorphism).
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String { // default method
String::from("shape")
}
}
struct Rect { w: f64, h: f64 }
struct Circle { r: f64 }
impl Rect {
fn new(w: f64, h: f64) -> Self { Rect { w, h } } // associated function (constructor)
fn is_square(&self) -> bool { self.w == self.h }
}
impl Shape for Rect {
fn area(&self) -> f64 { self.w * self.h }
fn name(&self) -> String { "rect".into() }
}
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
}
#[derive(Debug, Clone, PartialEq)] // auto-implement common traits
struct Point { x: i32, y: i32 }
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Rect::new(3.0, 4.0)), Box::new(Circle { r: 1.0 })];
for s in &shapes {
println!("{} {:.2}", s.name(), s.area());
}
let p = Point { x: 1, y: 2 };
let q = p.clone();
println!("{:?} {} {}", p, p == q, Rect::new(2.0, 2.0).is_square());
}
Output:
rect 12.00
shape 3.14
Point { x: 1, y: 2 } true true
Enums can carry data — perfect for modelling states:
enum Payment {
Cash,
Card { last4: String },
Upi(String),
}
fn describe(p: &Payment) -> String {
match p {
Payment::Cash => "cash".to_string(),
Payment::Card { last4 } => format!("card ending {last4}"),
Payment::Upi(id) => format!("UPI {id}"),
}
}
fn main() {
for p in [Payment::Cash, Payment::Card { last4: "4242".into() }, Payment::Upi("asha@upi".into())] {
println!("{}", describe(&p));
}
}
cash
card ending 4242
UPI asha@upi
10. Advanced Concepts
Ownership — every value has one owner; when the owner goes out of scope the value is dropped. Assigning a String moves it. Borrowing (&T shared, &mut T exclusive) lets you use a value without taking ownership. Rule: many & or one &mut at a time.
fn length(s: &String) -> usize { // borrow, don't take ownership
s.len()
}
fn shout(s: &mut String) { // mutable borrow
s.push('!');
}
fn main() {
let a = String::from("hi");
let b = a; // move: `a` can no longer be used
// println!("{a}"); // error: borrow of moved value
let c = b.clone(); // explicit deep copy
let mut d = c;
shout(&mut d);
println!("{} {} {}", b, d, length(&d));
}
hi hi! 3
Lifetimes tell the compiler how long references are valid:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
println!("{}", longest("ownership", "borrow"));
}
ownership
Error handling with Option and Result — no null, no exceptions:
use std::num::ParseIntError;
fn parse_sum(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x: i32 = a.trim().parse()?; // ? returns the error early
let y: i32 = b.trim().parse()?;
Ok(x + y)
}
fn main() {
match parse_sum("4", " 5") {
Ok(v) => println!("sum = {v}"),
Err(e) => println!("error: {e}"),
}
match parse_sum("4", "five") {
Ok(v) => println!("sum = {v}"),
Err(e) => println!("error: {e}"),
}
let maybe: Option<&str> = None;
println!("{}", maybe.unwrap_or("default"));
}
sum = 9
error: invalid digit found in string
default
Concurrency — the compiler prevents data races. Share data with Arc<Mutex<T>>:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..4 {
let c = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
*c.lock().unwrap() += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("total = {}", *counter.lock().unwrap());
}
total = 4000
Also learn: generics with trait bounds, iterators and closures, smart pointers (Box, Rc, RefCell), modules and crates, async/.await with Tokio, and testing with #[test].
⚠️ Common error:
cannot borrow 'v' as mutable because it is also borrowed as immutable— you hold a&reference while trying to modify. Finish using the shared borrow first (or restructure the code).
11. Examples with Output
Example 1 — Word frequency, sorted by count
use std::collections::HashMap;
fn main() {
let text = "the cat and the hat and the bat";
let mut freq: HashMap<&str, usize> = HashMap::new();
for w in text.split_whitespace() {
*freq.entry(w).or_default() += 1;
}
let mut pairs: Vec<_> = freq.into_iter().collect();
pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (w, c) in pairs.iter().take(3) {
println!("{w}: {c}");
}
}
the: 3
and: 2
bat: 1
Example 2 — Binary search returning Option
fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let (mut lo, mut hi) = (0usize, arr.len());
while lo < hi {
let mid = lo + (hi - lo) / 2;
if arr[mid] == target { return Some(mid); }
if arr[mid] < target { lo = mid + 1; } else { hi = mid; }
}
None
}
fn main() {
let a = [1, 3, 5, 7, 9, 11];
println!("{:?} {:?}", binary_search(&a, 7), binary_search(&a, 4));
}
Some(3) None
Example 3 — Iterator chain
fn main() {
let total: i32 = (1..=10).filter(|n| n % 2 == 1).map(|n| n * n).sum();
let words = ["apple", "kiwi", "banana"];
let longest = words.iter().max_by_key(|w| w.len()).unwrap();
println!("{total} {longest}");
}
165 banana
12. Practice Problems
- Read a line from standard input (
std::io::stdin().read_line) and print it reversed. - Write
fn is_prime(n: u64) -> booland print primes below 50. - Implement a
Stack<T>struct withpush,pop(returningOption<T>) andpeek. - Parse a list of
"name,age"lines into aVec<Person>, returningResulterrors for bad lines. - Model a traffic light with an
enumand anext()method. - Count word frequencies of a text file and print the top 5.
- Spawn 4 threads that each sum a quarter of a vector and combine the results.
- Solve the logic of Two Sum and Valid Parentheses in Rust (then submit in C++/Java/Python on Codify).
13. Interview Questions
1. What is ownership?
Each value has a single owner; when the owner goes out of scope the value is dropped. Assigning or passing a non-Copy value moves ownership.
2. What are the borrowing rules?
At any time you can have either any number of immutable references (&T) or exactly one mutable reference (&mut T), and references must always be valid.
3. What are lifetimes?
Annotations ('a) that describe how long references are valid, so the compiler can ensure no reference outlives the data it points to.
4. String vs &str?
String is an owned, heap-allocated, growable string. &str is a borrowed view (slice) into string data.
5. How does Rust handle errors?
Recoverable errors use Result<T, E> (propagated with ?); unrecoverable ones panic!. Missing values use Option<T> instead of null.
6. What is a trait?
A set of methods a type can implement — Rust's way of sharing behaviour, used for generics bounds and dynamic dispatch (dyn Trait).
7. Box, Rc and Arc?
Box<T> — single-owner heap allocation; Rc<T> — shared ownership (single thread, reference counted); Arc<T> — atomic reference counting for threads.
8. How does Rust prevent data races?
Through ownership and the Send/Sync traits — data shared across threads must be safely wrapped (e.g. Arc<Mutex<T>>), otherwise it doesn't compile.
9. Copy vs Clone?
Copy types (integers, bool, char) are duplicated implicitly with a bitwise copy; Clone is an explicit, possibly expensive, .clone().
10. What is unsafe?
A block where you can do things the compiler can't verify (raw pointers, FFI). It doesn't turn off the borrow checker; it marks code you must verify yourself.
14. Cheat Sheet & References
Cargo
# create, run, build, test, lint
cargo new app
cargo run
cargo build --release
cargo test
cargo fmt && cargo clippy
cargo add serde --features derive
Basics
let x = 5; let mut y = 10; const MAX: u32 = 100;
println!("{x} {:?} {:.2}", v, f);
let n: i32 = "42".parse().unwrap();
let s = format!("{}-{}", a, b);
Control flow
let v = if c { 1 } else { 2 };
match x { 1 => a(), 2 | 3 => b(), 4..=9 => c(), _ => d() }
for i in 0..n { } for (i, x) in v.iter().enumerate() { }
while cond { } let r = loop { break 5; };
if let Some(x) = opt { }
Collections
let mut v = vec![1, 2]; v.push(3); v.pop(); v.len(); v.sort(); v.contains(&2);
let s = String::from("a"); s.len(); s.chars(); s.split(' '); &s[0..1];
let mut m = HashMap::new(); m.insert(k, v); m.get(&k); *m.entry(k).or_insert(0) += 1;
let set: HashSet<i32> = HashSet::new(); VecDeque::new(); BinaryHeap::new();
v.iter().map(|x| x * 2).filter(|x| *x > 2).collect::<Vec<_>>();
Structs, enums, traits
#[derive(Debug, Clone, PartialEq)] struct P { x: i32 }
impl P { fn new(x: i32) -> Self { P { x } } fn get(&self) -> i32 { self.x } }
enum E { A, B(i32), C { name: String } }
trait T { fn f(&self) -> i32; }
impl T for P { fn f(&self) -> i32 { self.x } }
Ownership and errors
fn read(s: &String) { } fn change(s: &mut String) { }
let b = a.clone();
fn run() -> Result<i32, String> { let v = parse()?; Ok(v) }
opt.unwrap_or(0); res.expect("msg"); opt.map(|x| x + 1);
Official documentation