...

/

Explicit Type Conversions

Explicit Type Conversions

Let’s talk about explicit type conversions.

We'll cover the following...

As you have seen earlier in this chapter, there are cases where automatic conversions are not available:

  • Conversions from wider types to narrower types
  • Conversions from const to mutable
  • immutable conversions
  • Conversions from integers to enum values

If such a conversion is known to be safe, the programmer can explicitly ask for a type conversion by one of the following methods:

  • Construction syntax
  • std.conv.tofunction
  • std.exception.assumeUniquefunction
  • cast operator

Construction syntax

The struct and class construction syntax is available for other types as well:

DestinationType(value)

For example, the following conversion makes a double value from an int value, presumably to preserve the fractional part of the division operation:

D
import std.stdio;
void main() {
int i = 5;
// ...
const result = double(i) / 2;
writeln(result);
}

to() for most conversions

The to() function, which we have already used ...