Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Using typesystem to work with different units of measurement
Hello everyone!
Recently, I've been researching the newtype pattern to differentiate values of different use. This can be used to statically ensure correct use of units of measurement (for example, core::ops::Mul
trait can be implemented for density value and volume value to give the mass value). I also wonder whether values in different units of measurement can be represented by different types. In C++, there is a std::ratio
template, that implements compile-time rational arithmetic and can be used for unit conversion (C++ standard library uses it for representing time values). I've ported it to Rust using the generic_const_exprs
unstable feature. A number can be represented like this:
struct Mass<T: ct_ratio::StaticRatio>
{
value: f64,
ratio: T,
}
What do you think about it -- can const generics be used to create newtypes with arbitrary measurement units? (like, for mass, gram, kilogram, milligram, pound can be convertible into each other, and new mass units could be defined by changing the const generic values)
2 posts - 2 participants
🏷️ rust_feed