beginnerBasics
Enums Basic
Define enums with data variants and match on them.
Enums Basic
Define enums with data variants and match on them.
Difficulty
Beginner
Code
rust
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle(f64, f64),
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle(b, h) => 0.5 * b * h,
}
}
fn main() {
let c = Shape::Circle(5.0);
println!("Area: {:.2}", area(&c));
}Explanation
Enums define types with multiple variants. Variants can hold data. match must handle all variants.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the basics category to build a complete understanding of this topic.