Rust Enum Definition: A Comprehensive Guide for Beginners 🎯

beginner
14 min

Rust Enum Definition: A Comprehensive Guide for Beginners 🎯

Welcome to our Rust Enum Definition tutorial! In this lesson, we'll explore enums, a powerful and versatile data type in Rust. We'll cover everything from the basics to advanced usage, making it perfect for both beginners and intermediate learners. 📝

What are Enums? 💡

Enums (short for enumerations) are a way to define custom data types that consist of multiple possible values. They are a fundamental part of Rust's type system, providing a structured way to handle different cases in a single variable.

Creating an Enum 📝

To create an enum, we use the enum keyword followed by the enum name and a list of variants in curly braces. Here's an example of a simple enum that represents different shapes:

rust
enum Shape { Rectangle(f64, f64), Circle(f64), }

In this example, Rectangle and Circle are the variants of the Shape enum. Each variant can have associated data if enclosed in parentheses. For the Rectangle variant, we have two associated values: f64 representing the width and height. The Circle variant has one associated value for the radius.

Using Enums 💡

To create and use an enum instance, we use the enum name followed by the desired variant and any associated data.

rust
let square = Shape::Rectangle(2.0, 2.0); let circle = Shape::Circle(1.0);

We can access the associated data using the . operator.

rust
println!("The square's area is: {}", area_of_shape(square)); println!("The circle's area is: {}", area_of_shape(circle)); fn area_of_shape(shape: Shape) -> f64 { match shape { Shape::Rectangle(width, height) => width * height, Shape::Circle(radius) => 3.14 * radius * radius, } }

In the above example, we define a function area_of_shape that calculates the area of a given shape using pattern matching.

Enum Variants and Types 📝

Each variant in an enum can have a different data type associated with it. This allows us to create enums with complex and varied structures.

Here's an example of an enum that represents different types of expressions in a simple calculator:

rust
enum Expression { Number(f64), Add(Box<Expression>, Box<Expression>), Subtract(Box<Expression>, Box<Expression>), Multiply(Box<Expression>, Box<Expression>), Divide(Box<Expression>, Box<Expression>), } let add_expression = Expression::Add( Box::new(Expression::Number(3.0)), Box::new(Expression::Number(2.0)) );

In this example, the Add, Subtract, Multiply, and Divide variants take two Expression values as associated data. The Number variant has a f64 associated data.

Challenge 💡

Create an enum representing different types of fruits and calculate the total weight of a basket containing various fruits.

:::quiz Question: Create an enum representing different types of fruits and calculate the total weight of a basket containing various fruits.

rust
enum Fruit { Apple(f64), Banana(f64), // ... other fruit variants } let fruits_in_basket = vec![ Fruit::Apple(0.5), Fruit::Banana(0.3), // ... other fruits ]; let total_weight = calculate_total_weight(fruits_in_basket); println!("The total weight of the basket is: {}", total_weight); fn calculate_total_weight(fruits: Vec<Fruit>) -> f64 { // Your code here }

A:

rust
enum Fruit { Apple(f64), Banana(f64), // ... other fruit variants } let fruits_in_basket = vec![ Fruit::Apple(0.5), Fruit::Banana(0.3), // ... other fruits ]; let total_weight = calculate_total_weight(fruits_in_basket); println!("The total weight of the basket is: {}", total_weight); fn calculate_total_weight(fruits: Vec<Fruit>) -> f64 { fruits.iter().fold(0.0, |sum, fruit| match fruit { Fruit::Apple(weight) => sum + weight, Fruit::Banana(weight) => sum + weight, // ... other fruit variants }) }

Correct: A Explanation: The given solution creates an Fruit enum representing different types of fruits and calculates the total weight of a basket containing various fruits using a fold function. The calculate_total_weight function uses pattern matching to add the weight of each fruit in the basket.