Enums

View saved

Define variants

Each variant is a different possibility for the same type.

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

let m = Message::Write(String::from("hi"));

Match on enums

match must cover every variant (or use a catch-all).

match m {
    Message::Quit => println!("quit"),
    Message::Move { x, y } => println!("{x},{y}"),
    Message::Write(text) => println!("{text}"),
}

Why enums matter in Rust

Many APIs return enums instead of null. Option and Result are enums you will use constantly.

Enum habits

  • Put related variants in one enum
  • Store data in variants when each case needs different fields
  • Prefer enums over boolean pairs that hide meaning
  • Use match or if let to unpack

Comments

One comment per signed-in account. Comments are saved with this page’s URL.