Structs and Enums
A struct groups named fields and impl blocks add methods. An enum holds one of several variants, and each can carry data. match handles every variant.
Example
struct Rect { w: u32, h: u32 }
impl Rect {
fn area(&self) -> u32 { self.w * self.h }
}
enum Shape { Circle(f64), Square(f64) }
fn main() {
let r = Rect { w: 4, h: 5 };
println!("{}", r.area());
for s in [Shape::Circle(1.0), Shape::Square(2.0)] {
match s {
Shape::Circle(r) => println!("circle {:.2}", 3.14159 * r * r),
Shape::Square(a) => println!("square {}", a * a),
}
}
}Result
20 circle 3.14 square 4
Exercise
Add methods to a type.
Rect { }Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.