Introduction
Enums let you group related values under one name. Enum variants are the different options you can choose from inside that group.
Enums let you group related values under one name. Enum variants are the different options you can choose from inside that group.
enum Name {
Variant1,
Variant2,
Variant3
}Each variant is like a named option inside the enum.
Variants can hold data or be simple names.
enum Direction {
North,
East,
South,
West
}enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32) }
This program defines an enum with three variants. It prints a message depending on the variant.
enum TrafficLight { Red, Yellow, Green } fn print_light(light: TrafficLight) { match light { TrafficLight::Red => println!("Stop!"), TrafficLight::Yellow => println!("Get ready!"), TrafficLight::Green => println!("Go!"), } } fn main() { let light = TrafficLight::Yellow; print_light(light); }
You use :: to access enum variants.
Enums help make your code safer by forcing you to handle all cases.
Enum variants are named options inside an enum.
Variants can be simple or hold data.
Use enums to clearly represent choices or states.
enum variant in Rust?Red inside an enum Color?enum Name { Variant1, Variant2 }.Color with variant Red.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,
}
fn main() {
let s = Status::active;
}Status::active but enum defines Active with uppercase A.active is undefined.enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let msg = Message::Move { x: 10, y: 20 };
match msg {
Message::Quit => println!("Quit message"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
}
}msg is Message::Move { x: 10, y: 20 }.Message::Move { x, y } prints coordinates.Pass the test and this pattern moves unknown