Open chyvonomys opened 2 years ago
Related to #219, #91, #220
I kind of improved Units switch and conversion to be in one place and executed once:
use uom::si::*;
fn main() {
let src = [1.0f32, 2.0, 10.0]; // in atm
for dst_abbrev in ["kPa", "mm Hg", "in Hg", "atm", "psi", "km"] {
let units: Option<pressure::Units> = pressure::units().find(|x| x.abbreviation() == dst_abbrev);
if let Some(units) = units {
let conv: Option<fn(f32::Pressure) -> f32> = match units {
pressure::Units::kilopascal(_) => Some(|src| src.get::<pressure::kilopascal>()),
pressure::Units::millimeter_of_mercury(_) => Some(|src| src.get::<pressure::millimeter_of_mercury>()),
pressure::Units::inch_of_mercury(_) => Some(|src| src.get::<pressure::inch_of_mercury>()),
pressure::Units::atmosphere(_) => Some(|src| src.get::<pressure::atmosphere>()),
_ => None,
};
if let Some(conv) = conv {
for s in src {
let d = conv(f32::Pressure::new::<pressure::atmosphere>(s));
println!("{} {} -> {} {}", s, pressure::atmosphere::abbreviation(), d, dst_abbrev);
}
} else {
println!("`{}` is not supported", dst_abbrev);
continue
}
} else {
println!(
"{} is not a pressure unit, use one of {:?}", dst_abbrev,
pressure::units().map(|x| x.abbreviation()).collect::<Vec<_>>(),
);
continue
}
}
}
I'm thinking maybe this can be implemented as macro of an exhaustive match of all Units variants or something..
Hi, I'm trying to use this crate as a registry of units and conversions. I have a list of values (e.g pressure at different points) in one units (e.g kPa), and I want to convert all of them to other units known at runtime, user enters them.
So far I have figured out how to do it in a limited way for one value:
from_base
function that is exactly what I need in fact. But it is not exposed to users.dst_unit
, and no way to cover all enum variants automatically.This lack of dynamic units seems to be by design, but looks like it may be useful in cases like this. Maybe enabled by some feature gate.