Structs
Rust Enums
Defining Enums
Rust enums define variants with associated data for pattern matching.
Introduction to Enums in Rust
In Rust, enums are a powerful feature that allows you to define a type by enumerating its possible variants. Unlike enums in some other languages, Rust enums can also hold different types and amounts of associated data for each variant. This makes them particularly useful for defining a type that can represent multiple states or values, each potentially carrying additional data.
Basic Syntax of Rust Enums
Defining an enum in Rust is straightforward. Here is a simple example that defines an enum for different kinds of network events:
In this example, the NetworkEvent
enum has three variants: Connected
, Disconnected
, and DataReceived
. The DataReceived
variant is associated with a u32
data type, indicating that it carries an integer value.
Using Enums with Pattern Matching
One of the most powerful features of Rust enums is their integration with pattern matching. You can use a match
expression to handle each variant of an enum:
In this function, the match
expression is used to determine the variant of the NetworkEvent
and execute the corresponding block of code. This allows you to elegantly handle different cases based on the variant.
Enums with Multiple Data Types
Rust enums can hold different types of data for different variants. Here is an example of an enum that represents various shapes:
The Shape
enum defines three variants: Circle
, which holds a f64
representing the radius, Rectangle
, which holds a struct-like data with width
and height
, and Triangle
, which holds three f64
values representing the lengths of its sides.
Why Use Enums in Rust?
Enums are ideal in Rust when you want to represent a value that could be one of several different types. They provide a cleaner and more type-safe way of handling different states or configurations than using multiple struct
types or other data structures. Enums, combined with pattern matching, offer a powerful way to write concise and expressive code.
Structs
- Structs
- Struct Methods
- Enums
- Option
- Result
- Previous
- Struct Methods
- Next
- Option