Is there an opposite of .toString()?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Oct 14 03:47:29 UTC 2017


On Saturday, October 14, 2017 00:18:35 myst via Digitalmars-d-learn wrote:
> I'm sorry if this has been answered already, it seems like a very
> basic question.
>
> There is .toString() method convention for printing, but I can
> not find anything alike for reading. Is there something like
> operator>>() in C++? What's an ideomatic way of reading an object?

The function to use for conversions in general is std.conv.to. And really,
there isn't much of a reason to ever call toString. Functions like writeln,
format, and to may use it internally, but it's more or less an anti-pattern
to do so in your own code - especially if we're talking about generic code.
If you're looking to convert something to string, to!string works with
pretty much everything and toString works with considerably less. And if
there's a generic way to convert from string to something else, it's also
with to - e.g. to!int("42"). However, for that conversion to work, it either
has to be a built-in type so that to understands it, or the type will need a
constructor that takes a string. In general, in order to generically convert
to a user-defined type, either that target type must have a constructor that
accepts that source type, or the source type must define opCast or an alias
to convert to the target type. std.conv.to is very powerful, but it does
need to have something to work with. If anything approaching a standard
conversion exists, it can be done with std.conv.to; otherwise, it's going to
depend on the type.

I think that in general, you're going to find that converting to a string
works with most everything, but aside from built-in types, converting from a
string with std.conv.to is unlikely to work. _Some_ types do have
constructors that take strings, but most don't. Built-in types will work,
because std.conv.to understands how to do that conversion. For user-defined
types, either you're likely going to have to parse the string yourself, or
they may contain another function for doing the conversion (for instance
std.datetime.systime.SysTime uses toISOExtString and fromISOExtString to
convert to and from the ISO extended format for a date and time and has
other functions for other time formats).

You can also check out std.conv.parse, which acts similarly to std.conv.to,
but whereas to converts the entire string, parse converts the first portion
of a string and therefore is meant to allow for parsing multiple values from
a string.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list