Introduction
Enums let you group related values under one name. They help organize choices or states clearly.
Enums let you group related values under one name. They help organize choices or states clearly.
enum Name {
Variant1,
Variant2,
Variant3
}Each variant is a possible value of the enum.
Variants are written in CamelCase by convention.
enum Direction {
North,
East,
South,
West
}enum TrafficLight {
Red,
Yellow,
Green
}enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32) }
This program defines an enum for directions and prints a message based on the chosen direction.
enum Direction { North, East, South, West } fn print_direction(dir: Direction) { match dir { Direction::North => println!("Going North"), Direction::East => println!("Going East"), Direction::South => println!("Going South"), Direction::West => println!("Going West"), } } fn main() { let dir = Direction::East; print_direction(dir); }
You use :: to access enum variants.
Enums can have variants with or without extra data.
Using match helps handle all enum variants safely.
Enums group related values under one name.
Variants can be simple or hold extra data.
Use match to work with enum values clearly.
enum in Rust?Color with variants Red, Green, and Blue?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 set to Direction::East.Direction::East prints "Going East".enum Status {
Active,
Inactive,
Pending()
}enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}Message variant to move to coordinates (10, 20)?Move uses named fields inside braces: { x: i32, y: i32 }.Move { x: 10, y: 20 }.Pass the test and this pattern moves unknown