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

How do you create custom enums in Rust?

1个答案

1

Creating custom enums in Rust is an intuitive process. Enums (enumerations), commonly referred to as enums, allow you to define a type that can represent one of a finite set of values. Each variant can carry data of different types and quantities.

Defining Enums

The basic enum definition follows this syntax:

rust
enum Name { Variant1, Variant2(associated_data_type), Variant3 { field1: data_type, field2: data_type }, }

Example

Suppose we want to define an enum representing a traffic light, which can be in a red, yellow, or green state:

rust
enum TrafficLight { Red, Yellow, Green, }

In this simple example, the TrafficLight enum has three variants (Red, Yellow, Green), none of which carry additional data.

Enums with Data

Enums can express static variants while also associating data. For example, we can define an enum representing web server requests, which includes different request types and associated data:

rust
enum WebEvent { PageLoad, PageUnload, KeyPress(char), // Associated data of type char Paste(String), // Associated data of type String Click { x: i64, y: i64 }, // Associated data of a struct with two fields }

This example demonstrates advanced features. For instance, the KeyPress variant associates data of type char, while the Click variant associates data of a struct with two i64 fields.

Using Enums

After defining an enum, you can use it in functions to perform different operations, as shown below:

rust
fn inspect(event: WebEvent) { match event { WebEvent::PageLoad => println!("page loaded"), WebEvent::PageUnload => println!("page unloaded"), WebEvent::KeyPress(c) => println!("pressed '{}'", c), WebEvent::Paste(s) => println!("pasted "{}"", s), WebEvent::Click { x, y } => println!("clicked at x={}, y={}", x, y), } } // Usage example let pressed = WebEvent::KeyPress('x'); let pasted = WebEvent::Paste("my text".to_string()); let click = WebEvent::Click { x: 20, y: 80 }; inspect(pressed); inspect(pasted); inspect(click);

In this example, we define an inspect function that takes a WebEvent parameter. Using a match expression to handle different variants of the enum and perform corresponding actions. This pattern is very common and is one of Rust's powerful ways to work with enums.

Summary

By defining enums, you can effectively manage different data and states in Rust while maintaining type safety and clear logical structure. The use of enums makes the code both flexible and easy to maintain.

2024年8月7日 14:54 回复

你的答案