Crash Courses · Masters
Structs, Enums & Pattern Matching
Model data precisely and eliminate invalid states with enums
35 min read+170 XP on completionCert: Rust Crash Course
Tap any word in the text below to start reading from there.
Structs, Enums & Pattern Matching
Structs
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
impl Point {
// Associated function (like a static method / constructor)
fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
// Method — takes self reference
fn distance(&self, other: &Point) -> f64 {
((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
}
}
fn main() {
let p1 = Point::new(0.0, 0.0);
let p2 = Point::new(3.0, 4.0);
println!("Distance: {:.1}", p1.distance(&p2)); // 5.0
println!("{:?}", p1); // Debug: Point { x: 0.0, y: 0.0 }
}Enums with Data
#[derive(Debug)]
enum Shape {
Circle(f64), // radius
Rectangle(f64, f64), // width, height
Triangle { base: f64, height: f64 },
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle { base, height } => 0.5 * base * height,
}
}
}
fn main() {
let shapes = vec![
Shape::Circle(5.0),
Shape::Rectangle(3.0, 4.0),
Shape::Triangle { base: 6.0, height: 8.0 },
];
for s in &shapes {
println!("{:?} → area: {:.2}", s, s.area());
}
}Option<T> — No More Null
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 { None } else { Some(a / b) }
}
fn main() {
match divide(10.0, 2.0) {
Some(v) => println!("Result: {}", v),
None => println!("Division by zero"),
}
// Concise: if let
if let Some(v) = divide(9.0, 3.0) {
println!("Got: {}", v);
}
// Unwrap with default
let result = divide(5.0, 0.0).unwrap_or(0.0);
println!("{}", result); // 0
}Destructuring
let point = Point { x: 3.0, y: 4.0 };
let Point { x, y } = point;
println!("{} {}", x, y);
// Tuple destructuring
let (a, b, c) = (1, 2, 3);Match Guards
let n = 7;
match n {
x if x < 0 => println!("negative"),
0 => println!("zero"),
x if x % 2 == 0 => println!("positive even"),
_ => println!("positive odd"),
}Reading progress
0% read
In this module
struct
impl block
enum
match
0%