unit_system

Macro unit_system 

Source
unit_system!() { /* proc-macro */ }
Expand description

Create a quantity type for a given system of dimensions and units. The macro requires a list of statements separated with semicolons. There are five different types of statements, depending on the leading keyword:

  1. quantity_type NAME: The name of the quantity type that will be defined.
  2. dimension_type NAME: The name of the dimension type that will be defined. Appears in error messages but is otherwise hidden from the user.
  3. dimension: Define a new dimension. If no expression is given (as in dimension Length;), this will define a new base dimension. If an expression is given, it will define a type alias for a derived dimension (as in dimension Velocity = Length / Time).
  4. constant: Define a new constant. Example: constant ELECTRON_CHARGE = 1.602176634e-19 volts.
  5. unit: Define a new unit. If no expression is given and the #[base(...)] attribute is set, it will be the base unit for the given dimension. Example:
#[base(Length)]
#[symbol(m)]
unit meter

Derived units can be defined via expressions, such as

unit foot = 0.3048 * meter;

Unit statements may optionally be annotated with their resulting dimension to prevent bugs:

unit foot: Length = 0.3048 * meter;

Unit prefixes can be generated automatically using the #[prefix(...)] attribute for the unit statement. All metric prefixes (from atto- to exa-) can be generated automatically using the #[metric_prefixes] attribute for the unit statement. Aliases of the unit can be defined using the #[alias(...)] attribute. The symbol of the unit can be defined using the #[symbol(...)] attribute.

Example usage:

unit_system!(
    quantity_type Quantity;
    dimension_type Dimension;

    dimension Length;
    dimension Time;

    dimension Velocity = Length / Time;

    #[base(Length)]
    #[prefix(kilo, milli)]
    #[symbol(m)]
    unit meters;

    #[base(Time)]
    #[symbol(s)]
    unit seconds;

    unit hours: Time = 3600 * seconds;
    unit meters_per_second: Velocity = meters / seconds;
    unit kilometers_per_hour: Velocity = kilometers / hours;
    constant MY_FAVORITE_VELOCITY = 1000 * kilometers_per_hour;
);