Units of Measure

Define and track units to reduce dimensional-analysis bugs.

Units of Measure

Sounio has dedicated syntax for units of measure, so programs can carry dimensional meaning through the type system.

Unit Declarations

Units are declared at the top level, and currently require a trailing ;:

unit kg;
unit g = 0.001 * kg;
unit mg = 0.001 * g;

Units can be combined with multiplication, division, and exponents:

unit m;
unit s;
unit N = kg * m / s^2;

Quantities (Numeric + Unit)

The compiler supports a quantity type form:

Quantity[f64, mg]
Quantity[f64, kg*m/s^2]

To ascribe a unit type to a numeric literal, use @:

unit kg;
unit g = 0.001 * kg;
unit mg = 0.001 * g;

fn main() {
    let dose: Quantity[f64, mg] = 500.0@Quantity[f64, mg]
    let half = 250.0@Quantity[f64, mg]
    let total = dose + half
}

Spec vs Implementation

The long-term goal is compile-time unit checking and conversions that prevent mismatches (e.g., you can’t add a length to a mass).

Today, units and quantity types are parsed and representable, but full mismatch checking may not be enforced in every compiler mode yet. Prefer treating units as a correctness annotation until the unit checker is fully wired end-to-end.