Aliasing

The type statement can be used to give a new name to an existing type. Types
must have CamelCase names, or the compiler will raise a warning. The
exception to this rule are the primitive types: usize, f32, etc.

  1. // `NanoSecond` is a new name for `u64`.
  2. type NanoSecond = u64;
  3. type Inch = u64;
  4. // Use an attribute to silence warning.
  5. #[allow(non_camel_case_types)]
  6. type u64_t = u64;
  7. // TODO ^ Try removing the attribute
  8. fn main() {
  9. // `NanoSecond` = `Inch` = `u64_t` = `u64`.
  10. let nanoseconds: NanoSecond = 5 as u64_t;
  11. let inches: Inch = 2 as u64_t;
  12. // Note that type aliases *don't* provide any extra type safety, because
  13. // aliases are *not* new types
  14. println!("{} nanoseconds + {} inches = {} unit?",
  15. nanoseconds,
  16. inches,
  17. nanoseconds + inches);
  18. }

The main use of aliases is to reduce boilerplate; for example the IoResult<T> type
is an alias for the Result<T, IoError> type.

See also:

Attributes