Search code examples
tuplesvariable-assignmentdmultiple-return-values

How to assign simply multiple return values?


Traditionally this is done with out parameters, for example:

void notfun(ushort p, out ubyte r0, out ubyte r1)
{
    r0 = cast(ubyte)((p >> 8) & 0xFF);
    r1 = cast(ubyte)(p & 0xFF); 
}

With tuples it's possible to rewrite it as

auto fun(ushort p)
{
    import std.typecons;
    return tuple
    (
        cast(ubyte)((p >> 8) & 0xFF) ,
        cast(ubyte)(p & 0xFF)
    );
}

Unfortunately, the result is not assignable directly to a tuple of variable:

void main(string[] args)
{
    ushort p = 0x0102;
    ubyte a,b;
    // ugly brute cast!
    *(cast(ReturnType!(typeof(fun))*) &a) = fun(0x0102) ;
}

Is there a special syntax to allow something like

(a,b) = fun(0x0102);

or any other idiomatic way to do something similar ?


Solution

  • It's possible to implement PHP's list construct as a function in D:

    https://github.com/CyberShadow/ae/blob/777bdecd8d81030275531bfb8a393c2bb88b3d36/utils/array.d#L434-L463

    This will work for tuples and static arrays.