summary of some Rust basics, ownership, collections, iterators, traits, generics, and advanced fundamentals completed.
let x = 5;
let mut y = 10;
y = 20;Variables are immutable by default. Use mut to allow reassignment.
Conditional branching.
let age = 18;
if age >= 18 { println!("Adult"); }Cleaner pattern matching for one variant.
let opt = Some(5);
if let Some(v) = opt { println!("{}", v); }loop { break; }
while false {}
for i in 0..5 { println!("{}", i); }Use for for collections. Use while for conditions. Use loop for intentional infinite loops.
Signed: i8, i16, i32, i64, i128, isize Unsigned: u8, u16, u32, u64, u128, usize
f32 and f64
let pi: f64 = 3.14;
let inf = f64::INFINITY;
let nan = f64::NAN;Use f64 by default.
- One owner per value
&Timmutable borrow&mut Tmutable borrow- Cannot borrow mutable and immutable simultaneously (E0502)
- Cannot have multiple mutable borrows (E0499)
fn print(s: &String) {}let x = 5 as f64;let s = String::from("hello");
let s2: String = "world".into();use std::convert::TryInto;
let num: u8 = 5_i32.try_into().unwrap();let v = Vec::<i32>::new();Dynamic growable collection.
let mut v = vec![1,2,3];
v.push(4);v.iter(); // &T
v.into_iter(); // T (consumes)
v.iter_mut(); // &mut TUse .copied() when iterating references of Copy types.
Unique values only.
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(1);Requires Eq + Hash.
Key-value storage.
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);HashMap II: entry API
map.entry("a").or_insert(0);let arr = [1,2,3];
let slice: &[i32] = &arr[0..2];Fixed length. Slices borrow data.
let t = ("Alice", 25);
let (name, age) = t;Used to return multiple values.
let v = vec![1,2,3];
let sum: i32 = v.iter().sum();Transforms items.
let doubled: Vec<i32> = v.iter().map(|x| x * 2).collect();Keeps matching items.
let even: Vec<&i32> = v.iter().filter(|x| *x % 2 == 0).collect();for (i, val) in v.iter().enumerate() {}for i in (0..10).rev().step_by(2) {}String= owned&str= borrowed slice
let s = String::from("Hello");
let slice = &s;Concatenation:
let full = s + " world";Idiomatic to_string:
let num = 5.to_string();Represents presence or absence.
fn find() -> Option<i32> { Some(5) }Represents success or failure.
fn divide(a:i32,b:i32)->Result<i32,String>{
if b==0 {Err("zero".into())} else {Ok(a/b)}
}enum Status { Active, Inactive }Enum as wrapper:
enum Id { User(u32), Admin(u32) }match 1 {
1 => println!("One"),
_ => println!("Other")
}#[derive(Debug, Clone, PartialEq)]
struct User {
name: String,
age: u32,
}Attach methods to structs.
impl User {
fn new(name:String, age:u32)->Self{
Self{name,age}
}
}Associated functions & constants:
impl User {
const MAX_AGE: u32 = 150;
}Define shared behavior.
trait Speak { fn speak(&self); }Trait bounds:
fn print<T: Speak>(item:T){}Multiple constraints:
fn print<T: Speak + ToString>(item:T){}Supertraits:
trait A {}
trait B: A {}fn identity<T>(value:T)->T{ value }Enable comparisons.
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Point { x:i32 }Required for HashMap / HashSet keys.
use std::hash::Hash;let x = 5;
let r = &x;
println!("{}", *r);Non-Copy types can be dereferenced if not moved.
for v in vec.iter_mut() {
*v += 1;
}Cannot have two mutable borrows simultaneously.
let v = vec![(1,2),(3,4)];
let first: Vec<i32> = v.iter().map(|(a,_)| *a).collect();0..5
0..=5Safe and idiomatic conversions between types.
- INFINITY
- NEG_INFINITY
- NAN
Use is_nan() to check.
Understanding these makes you fluent in Rust.
Cause: Trying to mutably borrow while immutable borrow is active.
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s; // ❌ E0502Fix: Ensure immutable borrow ends before mutable borrow.
let mut s = String::from("hello");
{
let r1 = &s;
println!("{}", r1);
}
let r2 = &mut s; // ✅Cause: Multiple mutable references simultaneously.
let mut x = 5;
let r1 = &mut x;
let r2 = &mut x; // ❌ E0499Fix: Only one mutable reference at a time.
Cause: Ownership moved and then reused.
let s = String::from("hi");
let s2 = s;
println!("{}", s); // ❌ movedFix: Borrow or clone.
let s = String::from("hi");
let s2 = &s; // borrowCause: Type does not implement required trait.
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq)]
struct User { id: u32 }Fix: Derive required traits (Hash, Eq, PartialEq).
Cause: Expected one type, found another.
let x: i32 = "hello"; // ❌Fix: Ensure correct type or convert properly.
Cause: Method requires trait in scope.
use std::convert::TryInto;Bring required trait into scope.
let x = 5;
let r = &x; // immutable reference
let mut y = 10;
let r2 = &mut y; // mutable referenceRules:
- Many immutable OR one mutable
- Not both at same time
let x = 5;
let r = &x;
println!("{}", *r);Access value behind reference using *.
let s = String::from("hi");
let r = &s;
let cloned = r.clone();Clones underlying value if type implements Clone.
Copy types duplicate automatically (stack types).
let x = 5;
let y = x; // no moveCommon Copy types: integers, bool, char.
let arr = [1,2,3,4];
println!("{}", arr.len());Fixed size, same type.
Iterate characters in String.
let s = "abc";
for c in s.chars() {
println!("{}", c);
}let mut v = vec![1,2,3];
v.iter(); // &T
v.into_iter(); // T (consumes)
v.iter_mut(); // &mut Tlet mut v = vec![1,2,3];
for n in v.iter_mut() {
*n += 1;
}fn add_one(x: &mut i32) {
*x += 1;
}Cleaner pattern match.
let opt = Some(10);
if let Some(v) = opt {
println!("{}", v);
}use std::convert::TryInto;
let x: i32 = 10;
let y: u8 = x.try_into().unwrap();Used when conversion may fail.
let n = 5;
let s = n.to_string();Idiomatic string conversion.
Hint: look at what functions are available to you in the docs: https://doc.rust-lang.org/std/iter/trait.Iterator.html
let v = vec![1,2,3,4];
v.is_empty();
v.iter().count();
v.iter().min();
v.iter().max();
v.iter().sum::<i32>();
v.iter().nth(1);
v.iter().last();
let mut iter = v.iter();
iter.next();let mut v1 = vec![1,2];
let v2 = vec![3,4];
v1.extend(v2);enum Message {
Text(String),
Number(i32),
}Enums can store data (wrapper pattern).
fn print<T: Clone + ToString>(item: T) {}trait A {}
trait B: A {}B requires A.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Point { x: i32 }