Introduction
Enums help group related values under one name. They make code easier to read and safer by limiting possible options.
Enums help group related values under one name. They make code easier to read and safer by limiting possible options.
enum Name {
Option1,
Option2,
Option3
}Each option inside an enum is called a variant.
Variants can hold data, like numbers or strings, to store extra information.
enum Direction {
North,
East,
South,
West
}enum Shape {
Circle(f64),
Rectangle(f64, f64)
}This program defines a traffic light enum and prints what to do for each color.
enum TrafficLight { Red, Yellow, Green } fn action(light: TrafficLight) { match light { TrafficLight::Red => println!("Stop"), TrafficLight::Yellow => println!("Get ready"), TrafficLight::Green => println!("Go"), } } fn main() { let light = TrafficLight::Yellow; action(light); }
Using enums helps prevent invalid values because only defined variants are allowed.
Match statements with enums force you to handle every variant, reducing bugs.
Enums group related options under one name.
They can hold data to describe each option better.
Enums make code safer and easier to understand.
enum followed by the name and curly braces containing variants separated by commas.enum Direction {
North,
East,
South,
West,
}
fn main() {
let dir = Direction::East;
match dir {
Direction::North => println!("Going North"),
Direction::East => println!("Going East"),
Direction::South => println!("Going South"),
Direction::West => println!("Going West"),
}
}dir is assigned Direction::East.dir and prints the string for the matching variant. Since dir is East, it prints "Going East".enum Status {
Active,
Inactive,
}
fn main() {
let s = Status::active;
match s {
Status::Active => println!("Active"),
Status::Inactive => println!("Inactive"),
}
}Status::active instead of Status::Active.Pass the test and this pattern moves unknown