Welcome to Day 7 of your Rust journey! 🎉 Today, we’ll explore Enums in Rust, a powerful way to define types that can hold different but related kinds of data. Enums help in creating more readable and maintainable code. Let's get started! 🚀
Congratulations! 🎉 You've taken the first step in your journey to master the 30 Days of Rust programming challenge. In this challenge, you will learn the fundamentals of Rust and how to harness its power to write efficient, fast, and safe code. By the end of this journey, you'll have gained a solid understanding of Rust's core concepts and best practices, helping you become a confident Rustacean. 🦀
Feel free to join the 30 Days of Rust community on Discord, where you can interact with others, ask questions, and share your progress!
In Rust, enums allow you to define a type that can be one of several variants. We'll cover:
- How to declare and use enums.
- Using enums with
match
andif let
. - Defining methods on enums.
- Creating enums that carry data.
Ensure that you have your Rust environment set up correctly from Day 1. If you haven’t installed Rust yet, please refer to the setup instructions from Day 1.
Enums in Rust are declared using the enum
keyword, and they allow us to define a type that can be one of a few different variants.
Example:
enum Direction {
North,
South,
East,
West,
}
fn main() {
let move_direction = Direction::North;
match move_direction {
Direction::North => println!("Heading North!"),
Direction::South => println!("Heading South!"),
Direction::East => println!("Heading East!"),
Direction::West => println!("Heading West!"),
}
}
The match
statement is a powerful control flow construct that helps to match different enum variants.
Example:
enum TrafficLight {
Red,
Yellow,
Green,
}
fn action(light: TrafficLight) {
match light {
TrafficLight::Red => println!("Stop!"),
TrafficLight::Yellow => println!("Get Ready!"),
TrafficLight::Green => println!("Go!"),
}
}
fn main() {
let current_light = TrafficLight::Red;
action(current_light);
}
Enums can also have methods defined on them, similar to structs.
Example:
enum Vehicle {
Car(String),
Bike(String),
}
impl Vehicle {
fn drive(&self) {
match self {
Vehicle::Car(name) => println!("Driving a car: {}", name),
Vehicle::Bike(name) => println!("Riding a bike: {}", name),
}
}
}
fn main() {
let my_car = Vehicle::Car(String::from("Sedan"));
let my_bike = Vehicle::Bike(String::from("Mountain Bike"));
my_car.drive();
my_bike.drive();
}
Enums can also hold data, which makes them very versatile.
Example:
enum IpAddr {
V4(String),
V6(String),
}
fn main() {
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
println!("Home address: {:?}", home);
println!("Loopback address: {:?}", loopback);
}
Create a Rust program that defines an enum representing a payment method: CreditCard
, DebitCard
, Cash
, and PayPal
. Write a function to print the payment method used.
Template:
enum PaymentMethod {
CreditCard(String),
DebitCard(String),
Cash,
PayPal,
}
fn print_payment_method(method: PaymentMethod) {
match method {
PaymentMethod::CreditCard(card_number) => println!("Paid with Credit Card: {}", card_number),
PaymentMethod::DebitCard(card_number) => println!("Paid with Debit Card: {}", card_number),
PaymentMethod::Cash => println!("Paid with Cash"),
PaymentMethod::PayPal => println!("Paid with PayPal"),
}
}
fn main() {
let payment = PaymentMethod::CreditCard(String::from("1234-5678-9012-3456"));
print_payment_method(payment);
}
✅ Share your solution on GitHub and tag #30DaysOfRust on social media! Let the world see your progress! 🚀
- Create an enum called
Weather
with variants:Sunny
,Rainy
,Cloudy
, andWindy
. - Use a
match
statement to print out a message for each weather condition. - Define an enum
Device
that can hold valuesLaptop
,Tablet
, andPhone
, each containing a string (e.g., model name). Write a method to display the device information. - Create an enum called
TrafficLight
with variantsRed
,Yellow
, andGreen
. - Implement a function
get_light_duration
that returns the duration for each light:- Red: 30 seconds
- Yellow: 5 seconds
- Green: 20 seconds
- Use a match statement to print the duration of each traffic light.
- Write an enum
FileFormat
with variantsPDF
,Word
, andExcel
, each variant containing a file size (integer). Define a method on the enum to print the file format and size. - Create an enum
Status
with variants:Active
,Inactive
, andSuspended
. Use theif let
control flow to handle the enum. - Define a program that mimics an online order with enum
OrderStatus
containingPending
,Shipped
, andDelivered
. Write a function that takesOrderStatus
as input and prints out the current order status. - Create an enum called
Shape
with variantsCircle(f64)
for the radius,Rectangle(f64, f64)
for width and height, andTriangle(f64, f64, f64)
for the lengths of the three sides. - Implement a function
calculate_area
that takes aShape
and returns the area of the shape:- For a circle, use the formula πr².
- For a rectangle, use width * height.
- For a triangle, use Heron's formula.
- Test your function with different shapes and print the areas.
- We learned how to declare and use enums in Rust, including defining enums that hold data.
- We explored how to leverage the
match
statement with enums for effective control flow. - We defined methods on enums, making them more versatile and functional.
- Completed exercises to reinforce our understanding of enums.
🌟 Great job on completing Day 7! Keep practicing, and get ready for Day 8 where we will explore Collections in Rust!
Thank you for joining Day 7 of the 30 Days of Rust challenge! If you found this helpful, don’t forget to star this repository, share it with your friends, and stay tuned for more exciting lessons ahead!
Stay Connected
📧 Email: Hunterdii
🐦 Twitter: @HetPate94938685
🌐 Website: Working On It(Temporary)