Using typesystem to work with different units of measurement

⚓ Rust    📅 2025-07-08    👤 surdeus    👁️ 2      

surdeus

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

Read full topic

🏷️ rust_feed