Enums in Rust are a powerful feature that allows you to define a type by enumerating its possible variants. They are particularly useful for representing data that can be one of several possible types or states.
To define an enum in Rust, use the enum
keyword followed by the name of the enum and its variants:
enum Direction {
North,
South,
East,
West,
}
Each variant can be a unit-like struct, contain data, or even have different types of data:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
To create an instance of an enum, you use the enum name followed by two colons and the variant name:
let direction = Direction::North;
let message = Message::Write(String::from("Hello, Rust!"));
Enums are often used with pattern matching, which allows you to handle different variants of an enum:
match direction {
Direction::North => println!("Going north!"),
Direction::South => println!("Going south!"),
Direction::East => println!("Going east!"),
Direction::West => println!("Going west!"),
}
Rust's standard library includes a very useful enum called Option
. It's used to express the possibility of absence:
enum Option<T> {
Some(T),
None,
}
let some_number = Some(5);
let absent_number: Option<i32> = None;
The Option
enum is so common that it's included in the prelude; you don't need to bring it into scope explicitly. Its variants are also included: you can use Some
and None
directly without the Option::
prefix.
To fully leverage enums in Rust, you should also be familiar with:
Enums are a cornerstone of Rust's type system, providing a powerful way to express variants in your data structures. By mastering enums, you'll be able to write more expressive and safer Rust code.