Returning a tuple
Simen Kjaeraas
simen.kjaras at gmail.com
Fri Apr 27 06:40:37 PDT 2012
On Fri, 27 Apr 2012 14:52:08 +0200, Joseph Rushton Wakeling
<joseph.wakeling at webdrake.net> wrote:
> Hello all,
>
> Just recently I tried returning a Tuple from a function and received an
> error message about this not being allowed.
>
> Reading up a bit on the D site I'm not clear -- is it a determined
> policy for the language that it's not possible to return a tuple, or is
> it just something that has not yet been implemented?
>
> Assuming it's language policy or just not going to arrive for some time,
> any advice on how to get a similar effect of returning multiple values?
> I settled on defining a custom struct as return-type, but I'm not overly
> happy about it.
std.typecons has a type called Tuple, which is probably what you want:
import std.typecons;
Tuple!( int, string ) foo( ) {
return tuple( 42, "Hello, world!" );
}
void bar( ) {
auto a = foo( );
assert( a[0] == 42 );
assert( a[1] == "Hello, world!" );
}
There has been talk of making tuple support more built-in, but such has
not yet happened, and it is unclear when and if it will happen.
Oh, and there's more - Tuple supports named fields:
Tuple!( int, "amount", string, "color" ) baz( ) {
// I thought this worked, but apparently not:
//return tuple( 12, "red" );
return typeof( return )( 12, "red" );
}
void qux() {
auto b = baz( );
assert( b.amount == 12 );
assert( b.color = "red" );
}
More information about the Digitalmars-d-learn
mailing list