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)

You might find the Units of Measurements crate interesting uom - Rust

5 Likes

I absolutely love this in C++. It's amazing for chrono and such -- way better than Rust's one-size-fits-none Duration type.

That said, making it fit with Rust's generics is tough. GCE are still early, and it's not obvious how stuff like that will eventually work, so I'd be reticent about using a library that's built depending on something as unstable-and-uncertain as that.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.