Search code examples
typescastingd

What is the difference between to!string() and cast(string)


In D, what is the difference between the following:

import std.conv;
import std.stdio;

void main() {
    writeln(to!int(5.0));
}

and

import std.stdio;

void main() {
    writeln(cast(int) 5.0);
}

Solution

  • to!T handles a much wider range of conversions than a cast.

    For instance, int i = 5; writeln(cast(string)i); is an error -- there's no valid cast from int to string. But int i = 5; writeln(i.to!string); works and prints 5.

    Generally, casts are pretty much just reinterpreting the same bytes with a different type, with a few exceptions: casting between integer and floating point types (int → float produces the equivalent; float → int truncates), casting between class types (uses runtime type info to ensure the cast is valid; otherwise yields null), casting from a class to an interface (which kind of gives you a pointer to a fake object that forwards functions appropriately -- it's weird).

    to tries to do a lot more logical conversions, most frequently to and from strings.