Hello Rustaceans,
I've been through most of The Book, and now I'm trying something on my own to reinforce the concepts and test myself. I'm building a small library to perform various unit conversions: inches to millimeters, Fahrenheit to Celsius, that kind of thing. It's at a point where the structure is emerging, so I think it's a good time to get the opinion of the experts to help me with idiomaticness, maintainability, and efficiency.
The whole thing is checked in here. To summarize:
The different types of conversions are in their own modules:
src/length/mod.rs
src/mass/mod.rs
... etc.
I've chosen to implement each type of conversion as an enum with tuple struct variants:
#[derive(Debug, Copy, Clone)]
pub enum Unit {
Millimeters(f64),
Centimeters(f64),
Meters(f64),
Kilometers(f64),
Inches(f64),
Feet(f64),
Yards(f64),
Miles(f64),
}
I have a method to extract the numeric value:
impl Unit {
pub fn value(self) -> f64 {
match self {
Unit::Millimeters(x)
| Unit::Centimeters(x)
| Unit::Meters(x)
| Unit::Kilometers(x)
| Unit::Inches(x)
| Unit::Feet(x)
| Unit::Yards(x)
| Unit::Miles(x) => x,
}
}
// ...
}
And the conversions from one unit to another look like this:
impl Unit {
// ...
pub fn to_millimeters(self) -> Unit {
match self {
Unit::Millimeters(x) => Unit::Millimeters(x),
Unit::Centimeters(x) => Unit::Millimeters(x * 10.0),
Unit::Meters(x) => Unit::Millimeters(x * 1_000.0),
Unit::Kilometers(x) => Unit::Millimeters(x * 1_000_000.0),
// Not fully implemented yet
_ => Unit::Millimeters(1.0),
}
}
// similar implementations for to_centimeters, to_meters, etc....
}
I also re-export the modules from the top-level:
pub use length::Unit as Length;
Am I on a good path here? The thing that concerns me about the functions is how quickly they would balloon if I introduce even one more variant. But maybe that's unavoidable no matter how I implement. Also the value
method seems like there should be a more direct way to access that value, but I couldn't find it.
What about ownership? I'm still pretty fuzzy on this. I think by implementing the Copy
and Clone
traits I've avoided issues with that, but I'm not sure.
Thanks for any advice you can give me,
Eric