In Rust, if you want to access values within an enum, you typically use pattern matching. The match keyword in Rust allows you to destructure enum values using different patterns and respond to various cases.
Here is a basic example demonstrating how to access enum values in Rust:
First, we define an enum type Message with several variants, including those storing different types of data:
rustenum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), }
This enum has four variants:
Quithas no associated data.Movecontains a struct with fieldsxandy.Writecontains a singleString.ChangeColorcontains threei32values.
Now, if you want to inspect a Message enum value and extract its data, you can use a match expression:
rustfn main() { let msg = Message::ChangeColor(0, 160, 255); match msg { Message::Quit => { println!("The Quit variant has no data to destructure."); }, Message::Move { x, y } => { println!("Move in the x direction {} and in the y direction {}", x, y); }, Message::Write(text) => { println!("Text message: {}", text); }, Message::ChangeColor(r, g, b) => { println!("Change the color to red {}, green {}, and blue {}", r, g, b); }, } }
In this example, the match expression executes different code blocks based on the value of msg. For ChangeColor, it destructures three i32 values and prints them as r, g, and b.
This is an example of how to safely and effectively access and handle enum values in Rust. Using a match expression not only ensures code safety by forcing you to handle every possible variant of the enum but also directly destructures the data within the enum.