Destructuring extracts values from structured values, such as enum variants, through pattern matching. A match arm binds the contained value while checking which variant is present. section 2.5.1
Extracting an enum payload
An enum can store data in a variant: NotDivisible(i32). Matching FizzBuzzValue::NotDivisible(num) both confirms the variant and binds its i32 payload for printing. Rust therefore prevents direct access without checking the value's variant first. section 2.5.1
Listing 2.26 FizzBuzzValue enum holding a number not divisible by 3 or 5
enum FizzBuzzValue {
Fizz,
Buzz,
FizzBuzz,
NotDivisible(i32), #1
}
fn main() {
for i in 1..101 {
print_fizzbuzz(i);
}
}
fn print_fizzbuzz(x: i32) {
match fizzbuzz(x) {
FizzBuzzValue::FizzBuzz => {
println!("FizzBuzz");
}
FizzBuzzValue::Fizz => {
println!("Fizz");
}
FizzBuzzValue::Buzz => {
println!("Buzz");
}
FizzBuzzValue::NotDivisible(num) => { #2
println!("{}", num);
}
}
}
fn fizzbuzz(x: i32) -> FizzBuzzValue {
if x % 3 == 0 && x % 5 == 0 {
FizzBuzzValue::FizzBuzz
} else if x % 3 == 0 {
FizzBuzzValue::Fizz
} else if x % 5 == 0 {
FizzBuzzValue::Buzz
} else {
FizzBuzzValue::NotDivisible(x) #3
}
}
Trace the complete FizzBuzz example, including the enum payload, destructuring match arm, and value returned by the function. section 2.5.1





