RRust By Example
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

This example demonstrates how to use enums basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples