Skip to content
Justice Tech School

Enums with Data

Each enum variant can hold different data. match extracts it. Option and Result are enums in the standard library.

Example
enum Shape { Circle(f64), Rect { w: f64, h: f64 }, Unit }
fn area(s: &Shape) -> f64 {
    match s {
        Shape::Circle(r) => 3.14 * r * r,
        Shape::Rect { w, h } => w * h,
        Shape::Unit => 1.0,
    }
}
fn main() {
    println!("{} {}", area(&Shape::Rect { w: 2.0, h: 3.0 }), area(&Shape::Unit));
}

Result

6 1

Exercise

Declare an enum.

 Shape { A, B }

Quiz Test

Can enum variants hold data?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.