An enum is a Rust sum type whose variants represent a restricted set of possible states. Variants can carry data, expose methods, and work naturally with pattern matching. section 7.3
Representing success or failure
Model an operation that either succeeds with a value or fails with a message: `Either<T>` has `Success(T)` and `Failure(String)` variants. A caller must match both possibilities, making failure handling explicit. section 7.3
enum Either<T> {
Success(T),
Failure(String),
}
Defines a generic enum with success and failure variants carrying different data. section 7.3
fn calculate_answer_to_life() -> Either<i32> {
Either::Success(42)
}
fn main() {
match calculate_answer_to_life() {
Either::Success(answer) => {
println!("Got the answer: {answer}");
}
Either::Failure(_) => {
println!("Should handle failure");
}
}
}
Uses pattern matching to extract a successful answer and handle failure. section 7.3
impl<T> Either<T> {
fn map(self, function: fn(T) -> T) -> Either<T> {
match self {
Either::Success(answer) => {
return Either::Success(function(answer))
}
// if it's not a success, no need to do anything
_ => self
}
}
}
fn main() {
let two = Either::Success(1).map(|v| v + 1);
}
Adds a `map` method that transforms a success value while leaving failures unchanged. section 7.3






















