units
Units of Measure for Rust. Easy to use, type-safe and customizable.
Usage (Example)
extern crate units;
// It is recommended to put units inside a separate module
// Import the unit constants and also the dimensionless unit `one`
use ;
Use cargo run --example basics
to run this example.
There is an alternative, safer syntax for assigning units to values using function call operator overloading, but this is currently only available in Rust nightly. See examples/basics.rs for both versions.
How does it work?
The macro invocation shown above will generate a struct MyUnits<U,T=f64>
, where the first type parameter is a special marker to get the dimension right (it contains exponents for every base unit, encoded as type-level integers). Meter
, Second
and Mile
will be type aliases for this marker type with the correct exponents.
The second type parameter denotes the wrapped numeric type (defaults to f64
). The autogenerated child modules my_units::f64
and my_units::f32
then both contain the constants m
, s
and mile
, each of the correct dimension and wrapping the value 1.0
. For example, f64::m
is of type MyUnits<Meter, f64>
.
Additionally, the type One
and the constant one
are provided for dimensionless values, and only those can be unwrapped using the Deref
trait (this works automatically for method calls, but sometimes needs to be made explicit using the *
prefix operator, see the example above).