1. Enums — algebraic data types
- Enums are powerful — each variant can carry data.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
- Match exhaustively — catches all cases at compile time.
2. Option<T> — no null
Option<T>:Some(T)orNone— encodes “might be missing”.
let x: Option<i32> = Some(5);
let y: Option<i32> = None;
if let Some(v) = x { println!("value {}", v); }
unwrap()— panic if None;expect("msg")— nicer panic;?propagates.- No null pointer —
Noneinstead.
3. Result<T, E> — no exceptions
Result<T, E>:Ok(T)orErr(E)— encodes failure reason.
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse()
}
?operator: onErr, return early from the function; onOk, unwrap value.
fn main() -> Result<(), std::io::Error> {
let content = std::fs::read_to_string("f.txt")?; // propagates error
println!("{content}");
Ok(())
}
4. Structs & methods
struct Point { x: i32, y: i32 }
impl Point {
fn new(x: i32, y: i32) -> Self { Self { x, y } }
fn dist(&self) -> f64 { ((self.x*self.x + self.y*self.y) as f64).sqrt() }
}
implblocks attach methods;Self= the struct type.&selfborrows;&mut selfmutates;selfconsumes.
5. Pattern matching
match= exhaustive;if letfor single-arm convenience;while letfor loops.- Destructuring tuples/structs/enums.
_wildcard catches the rest;..ignores trailing fields.- Guards:
match n { x if x > 5 => ..., }.
6. Interview checkpoint
- Enums carry data; exhaustiveness of match.
- Option vs Result — when each is used.
?operator and early return.- &self vs &mut self vs self.
- Struct literal shorthand + update syntax.
Premium Content
Unlock Part 2: Enums, Option, Structs & Pattern Matching and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans