乐闻世界logo
搜索文章和话题

How do you access enum values in Rust?

1个答案

1

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:

rust
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), }

This enum has four variants:

  • Quit has no associated data.
  • Move contains a struct with fields x and y.
  • Write contains a single String.
  • ChangeColor contains three i32 values.

Now, if you want to inspect a Message enum value and extract its data, you can use a match expression:

rust
fn 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.

2024年8月7日 17:15 回复

你的答案