Sub topic 2
Adding Behavior with `impl` and Patterns
Assume basic Rust syntax, structs, tuples, ownership, and borrowing. Rust enums can hold different kinds of data. An impl block adds methods that operate on those variants.
Methods on enums
Each match arm can destructure a variant and use its fields. The compiler checks that every variant is handled.
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
fn main() {
let shape = Shape::Rectangle {
width: 2.0,
height: 3.0,
};
println!("{:.1}", shape.area());
}`Option`: handling absent values
Option<T> represents either Some(value) or None. Use it when a value might be missing.
fn first_even(values: &[i32]) -> Option<i32> {
values.iter().copied().find(|n| n % 2 == 0)
}A match handles both possibilities:
match first_even(&[1, 3, 4]) {
Some(value) => println!("found {value}"),
None => println!("no even value"),
}For one interested case, if let is shorter:
if let Some(value) = first_even(&[1, 3, 4]) {
println!("{value}");
}Pattern kinds and destructuring
Patterns can match literals, ranges, alternatives, and a fallback wildcard.
fn classify(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
1..=9 => "small",
10 | 100 => "selected",
_ => "other",
}
}Destructuring takes fields out of tuples, structs, and nested variants:
enum Command {
Move { point: (i32, i32) },
Draw(Shape),
}
fn describe(command: &Command) {
match command {
Command::Move { point: (x, y) } => println!("move to {x}, {y}"),
Command::Draw(Shape::Circle { radius }) => println!("circle: {radius}"),
Command::Draw(_) => println!("other shape"),
}
}Guards and `@` bindings
A guard adds a condition after a pattern. An @ binding keeps the matched value available:
fn kind(n: i32) -> &'static str {
match n {
value @ 1..=9 if value % 2 == 0 => "small even",
1..=9 => "small odd",
_ => "other",
}
}Exercise
Which pattern matches an even number from 1 through 9 while keeping that number in a variable named value?
Show answer
value @ 1..=9 if value % 2 == 0