Methods on Enums
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
Click here to reveal hints
- 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.
No run yet
Press
Run to execute your code and see test results here.