Explicit Type Conversions
Explore explicit type conversions in D programming to handle cases where automatic conversions are unavailable. Understand how to use construction syntax, to(), assumeUnique(), and cast operator for safe conversions between types such as integers, enums, pointers, and immutable data. Gain the skills to manage type safety and program correctness effectively in advanced D code.
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
constto mutable immutableconversions- Conversions from integers to
enumvalues
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.tofunctionstd.exception.assumeUniquefunctioncastoperator
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 ...