Rust Traits and Enums
A trait describes shared behaviour (like an interface). An enum is a type that can be one of several variants, each able to carry data.
ExampleRust
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Rect(f64, f64);
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.0 * self.0 }
}
impl Shape for Rect {
fn area(&self) -> f64 { self.0 * self.1 }
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn show(m: &Message) -> String {
match m {
Message::Quit => "quit".to_string(),
Message::Move { x, y } => format!("move to {},{}", x, y),
Message::Write(t) => format!("write {}", t),
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Rect(2.0, 3.0))];
for s in &shapes {
println!("{:.2}", s.area());
}
println!("{}", show(&Message::Move { x: 1, y: 2 }));
println!("{}", show(&Message::Write("hi".to_string())));
println!("{}", show(&Message::Quit));
}Output
3.14 6.00 move to 1,2 write hi quit
Quick check
What can an enum variant carry?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.