Is there an opposite of .toString()?
myst
a at b.c
Sat Oct 14 12:37:31 UTC 2017
On Saturday, 14 October 2017 at 03:47:29 UTC, Jonathan M Davis
wrote:
> 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).
This is not what I asked about.
> 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.
This is what I asked about. Thanks.
More information about the Digitalmars-d-learn
mailing list