Type conversions

Syntactically a type conversion is like a procedure call, but a type name replaces the procedure name. A type conversion is always safe in the sense that a failure to convert a type to another results in an exception (if it cannot be determined statically).

Ordinary procs are often preferred over type conversions in Nim: For instance, $ is the toString operator by convention and toFloat and toInt can be used to convert from floating point to integer or vice versa.

A type conversion can also be used to disambiguate overloaded routines:

  1. proc p(x: int) = echo "int"
  2. proc p(x: string) = echo "string"
  3. let procVar = (proc(x: string))(p)
  4. procVar("a")

Since operations on unsigned numbers wrap around and are unchecked so are type conversion to unsigned integers and between unsigned integers. The rationale for this is mostly better interoperability with the C Programming language when algorithms are ported from C to Nim.

Exception: Values that are converted to an unsigned type at compile time are checked so that code like byte(-1) does not compile.

Note: Historically the operations were unchecked and the conversions were sometimes checked but starting with the revision 1.0.4 of this document and the language implementation the conversions too are now always unchecked.