Enums in Rust can have associated functions and methods, just like structs. These methods make it easier to encapsulate behavior directly within the enum.
In this challenge, you'll model the statuses of different vehicles and implement methods to describe their behavior.
Your Task
Create an enum VehicleStatus with the following variants:
Parked— a unit variant representing a parked vehicle.Driving { speed: u32 }— a named field variant representing a vehicle driving at a certain speed.BrokenDown(String)— a tuple variant with aStringdescribing the reason for the breakdown.
Implement the following methods for VehicleStatus:
-
is_operational(&self) -> bool:- Returns
trueif the vehicle is eitherParkedorDriving. - Returns
falseif the vehicle isBrokenDown.
- Returns
-
description(&self) -> String:- Returns
"The vehicle is parked."forParked. - Returns
"The vehicle is driving at {speed} km/h."forDriving { speed }. - Returns
"The vehicle is broken down: {reason}."forBrokenDown(reason).
- Returns
Hints
<details> <summary>Click here to reveal hints</summary>- Use a
matchexpression inside the methods to handle each variant. - Remember to use
&selffor the methods since they should not consume the enum. - Use
format!to construct strings with dynamic values, such asspeedandreason.
pub enum VehicleStatus {// Define the VehicleStatus variants here}impl VehicleStatus {pub fn is_operational(&self) -> bool {// Your code here...}pub fn description(&self) -> String {// Your code here...}}// Example use casepub fn main() {let parked = VehicleStatus::Parked;assert!(parked.is_operational());assert_eq!(parked.description(), "The vehicle is parked.");let driving = VehicleStatus::Driving { speed: 80 };assert!(driving.is_operational());assert_eq!(driving.description(), "The vehicle is driving at 80 km/h.");let broken_down = VehicleStatus::BrokenDown("Flat tire".to_string());assert!(!broken_down.is_operational());assert_eq!(broken_down.description(),"The vehicle is broken down: Flat tire.");}