D is a strongly typed language, which means converting between types often has to be done explicitly. The language's built-in cast
operator only works when the types are already mostly compatible, for example int
to short
, or in cases where the user has defined an opCast
function. This doesn't cover the very common need of converting strings to integers and vice versa. That's where Phobos' std.conv
module is helpful.
Now it's time to perform type conversions by executing the following steps:
Import
std.conv
.Use the
to
function as follows:import std.conv; auto converted = to!desired_type(variable_to_convert);
This is pretty simple, and it works for a lot of types.
To convert a string to an integer, use the following line of code:
auto a = to!int("123"); // a == 123
That's all you have to do!