Enum Basics
Defining a Simple Enum
An enum defines a type whose value can be exactly one of a fixed set of named variants, useful for representing a closed set of possibilities.
Example: Defining a Simple Enum
#[derive(Debug)]
enum Direction {
North,
South,
East,
West,
}
fn main() {
let heading = Direction::North;
println!("{:?}", heading);
}
Login to try C/C++/Java/PHP code in the editor
Enums With Data
Unlike simple labels, Rust enum variants can carry their own associated data, and different variants can carry different types and amounts of data.
Example: Enums With Data
#[derive(Debug)]
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}
fn main() {
let shapes = [Shape::Circle(2.0), Shape::Rectangle(3.0, 4.0)];
for s in shapes.iter() {
println!("{:?}", s);
}
}
Login to try C/C++/Java/PHP code in the editor
Matching on an Enum
match is the primary way to inspect which variant an enum value holds and to extract any data it carries, with a separate arm for each possible variant.
Example: Matching on an Enum
enum TrafficLight {
Red,
Yellow,
Green,
}
fn main() {
let light = TrafficLight::Yellow;
match light {
TrafficLight::Red => println!("Stop"),
TrafficLight::Yellow => println!("Slow down"),
TrafficLight::Green => println!("Go"),
}
}
Login to try C/C++/Java/PHP code in the editor
Comparing Enum Values
Deriving PartialEq on an enum allows comparing its values directly with ==, which is useful for simple checks without writing a full match.
Example: Comparing Enum Values
#[derive(PartialEq, Debug)]
enum Status {
Active,
Inactive,
}
fn main() {
let current = Status::Active;
println!("Is active: {}", current == Status::Active);
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting an enum variant can carry its own data, not just be a plain label like in some other languages.
- Trying to compare enum variants with
==before derivingPartialEqon the enum. - Assuming enum variant names are globally unique -- they must be qualified with
EnumName::Variantunless imported.
- An enum defines a type that can be exactly one of several named variants.
- Variants can optionally carry associated data, including different data per variant.
- Enum values are typically handled with
matchto branch on which variant is present. - Deriving traits like
DebugandPartialEqon an enum enables printing and comparison.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: