Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 2: Enums, Option, Structs & Pattern Matching
RUST

Part 2: Enums, Option, Structs & Pattern Matching

Review Rust enums, Option and Result, structs, match expressions, and pattern matching fundamentals.

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) or None — 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 — None instead.

3. Result<T, E> — no exceptions

  • Result&lt;T, E&gt;: Ok(T) or Err(E) — encodes failure reason.
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
    s.parse()
}
  • ? operator: on Err, return early from the function; on Ok, 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() }
}
  • impl blocks attach methods; Self = the struct type.
  • &self borrows; &mut self mutates; self consumes.

5. Pattern matching

  • match = exhaustive; if let for single-arm convenience; while let for 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.

My Private Notes

Notes are auto-saved locally to this device.