Nullable!T containing the converted value, or null if conversion failed.var.tryAs
Attempt to convert the stored value to type T, returning a Nullable!T.
Unlike as!T, which returns T.init on failure (making it impossible to distinguish between "the value was T.init" and "conversion failed"), tryAs!T returns a Nullable!T that is null when conversion fails.
Conversion rules:
- If the current type is
Type.NULL, returns a nullNullable!T. - If the stored type matches
Tor can be converted viastd.conv.to, returns the value. - If conversion fails (e.g., type mismatch or
std.convthrows), returns a nullNullable!T.
Parameters
T | The target type to convert to. |
Returns
A
Examples
var v = 42;
auto result = v.tryAs!int;
assert(!result.isNull && result.get == 42);
var s = "not a number";
auto bad = s.tryAs!int;
assert(bad.isNull); // conversion failed
var zero = 0;
auto zeroResult = zero.tryAs!int;
assert(!zeroResult.isNull && zeroResult.get == 0); // distinguishable from failure