Multiple return values...

bearophile bearophileHUGS at lycos.com
Fri Mar 16 16:48:02 PDT 2012


Simen K.:

> Now, a pattern that our productive friend bearophile posted earlier was  
> this:
> 
> int[] foo();
> 
> (auto a, b) = foo();
> 
> --->
> 
> auto __t = foo();
> assert( __t.length > 0 );
> auto a = __t[0];
> auto b = __t[1..$];
> 
> Is this something we might also want?

That's not a good idea, because you don't know much about what 'b' contains.

Time ago I have written an example vaguely like that, but it was in the Python3 version. So a more similar translation is:

auto (a, $b) = foo();

The $ means: 'unpack all the remaining items inside the b tuple'. A similar syntax is cute to have, but it's not that important because it's not a very common need. And if people think it's so important, then it's possible to add it later (it's a purely incremental feature over the basic tuple unpacking syntax).

What's more commonly userful instead is tuple unpacking in foreach (this isn't the final syntax, it's just an idea) (Hara is willing to support this first one):

void spam((int x, int y)) {}
auto bar = [tuple(1,2,), tuple(3,4)];
foreach (tuple(x, y); bar) {}

And in function signatures (this is not the same as using tupleof at the call point):

void spam(tuple(int x, int y)) {}
spam(tuple(1,2))

Bye,
bearophile


More information about the Digitalmars-d mailing list