0PricingLogin
Learn Rust Coding · Lesson

Enums with Data

Attach values to variants.

Variants Can Hold Data

So far our variants were just names. In Rust, a variant can also carry data inside parentheses.

This lets a single enum describe both the kind of value and the value itself.

enum Message {
    Quit,
    Move(i32, i32),
    Write(String),
}

A Variant with One Value

Put a type in parentheses to attach one piece of data to a variant.

Here Celsius(f64) means the Celsius variant holds a f64 number. You supply that number when you build the value.

enum Temperature {
    Celsius(f64),
    Fahrenheit(f64),
}

fn main() {
    let t = Temperature::Celsius(21.5);
    println!("Created a temperature");
}

All lessons in this course

  1. Defining Your First Enum
  2. Matching on Enum Variants
  3. Enums with Data
  4. Match Guards and Bindings
← Back to Learn Rust Coding