Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Defining Enums in Rust

What is an Enum?

An Enum (short for "enumeration") is a powerful feature in Rust that allows you to define a type that can have multiple distinct values. Each value is called a variant. Enums are particularly useful for representing a choice between different types or states.

Defining an Enum

To define an enum in Rust, you use the enum keyword followed by the name of the enum and its variants. Here's a simple example:

Example of Defining an Enum:

enum Direction { Up, Down, Left, Right }

In this example, we have defined an enum called Direction with four variants: Up, Down, Left, and Right.

Using Enums

Once you have defined an enum, you can create instances of that enum and use them in your code. Here is how you can create an instance of the Direction enum:

Creating an Enum Instance:

let move = Direction::Up;

In this code snippet, we create a variable move of type Direction and assign it the variant Up.

Matching Enums

Enums are often used with pattern matching to execute different code depending on the variant. Here is an example:

Matching on Enum Variants:

match move { Direction::Up => println!("Moving Up!"), Direction::Down => println!("Moving Down!"), Direction::Left => println!("Moving Left!"), Direction::Right => println!("Moving Right!"), }

In this example, we use a match statement to print a message based on the value of move. The code will execute the branch that matches the variant.

Enums with Data

Enums can also hold data. Each variant can have different types and amounts of associated data. Here’s an example:

Defining an Enum with Data:

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

In this example, the Message enum has three variants: Quit (with no data), Move (with two i32 fields), and Write (with a String field).

Conclusion

Enums in Rust provide a robust way to define types that can take on multiple forms. They are essential for creating flexible and safe code, especially when combined with pattern matching. Understanding how to define and use enums is a fundamental skill for any Rust programmer.