var.tryAs

Nullable!T tryAs(T)() const @safe

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 null Nullable!T.
  • If the stored type matches T or can be converted via std.conv.to, returns the value.
  • If conversion fails (e.g., type mismatch or std.conv throws), returns a null Nullable!T.

    Parameters

    TThe target type to convert to.

    Returns

    A Nullable!T containing the converted value, or null if conversion failed.

    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