Welcome back to CodeYourCraft! Today, we're diving into the world of enum variants in Rust. If you're new to Rust, don't worry! We'll cover everything you need to know, from the basics to advanced examples.
Enums (short for enumerations) are a powerful feature in Rust that allow us to define custom data types consisting of multiple variants. Enums can be used to represent things like different types of errors, different states of a system, or even different shapes in a game.
Each variant in an enum can have a different set of fields, allowing us to model complex data structures with flexibility. In this lesson, we'll focus on understanding enum variants and how to use them.
enum Shape {
Circle { radius: f64 },
Rectangle { length: f64, width: f64 },
}In the example above, we've defined an enum Shape with two variants: Circle and Rectangle. Each variant has different fields: radius for Circle and length and width for Rectangle.
Now let's see how to create and use enums.
fn main() {
let shape1 = Shape::Circle { radius: 5.0 };
let shape2 = Shape::Rectangle { length: 4.0, width: 3.0 };
println!("Shape 1 area: {}", area(&shape1));
println!("Shape 2 area: {}", area(&shape2));
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle { radius } => 3.14 * radius * radius,
Shape::Rectangle { length, width } => length * width,
}
}In the main function, we create two shapes and calculate their areas using the area function. The area function uses a match statement to handle each variant and calculate the area accordingly.
Question: What does the & symbol represent before Shape in the area function?
A: Dereference operator B: Reference operator C: Copy operator
Correct: B
Explanation: The & symbol represents a reference to the Shape variable, allowing us to work with a reference to the data without taking ownership of it.
Stay tuned for more Rust tutorials at CodeYourCraft! Remember, practice makes perfect. Keep coding, and happy learning! 🥳