How to unpack a tuple into multiple variables?

Gary Chike chikega at gmail.com
Tue Feb 6 05:36:03 UTC 2024


On Monday, 5 February 2024 at 21:21:33 UTC, TTK Ciar wrote:
> My mnemonic: "put" is "tup" backwards, and undoes what tuple 
> does.

Very clever mnemonic TTK Ciar! :) After reviewing the various 
solutions, the one I seem to gravitate towards is based on the 
one you presented, well, at least for now until a direct 
implementation is implemented (crossing my fingers!). I really 
appreciate everyone's help! :-)

```d
import std.stdio;
import std.meta; // AliasSeq!
import std.typecons : tuple;

void main() {
     // Create a tuple
     auto myTuple = tuple(10, "hello", [1, 2]);
     auto myTuple1 = tuple(42, "bye", [3, 4]);

     // Declare some variables to unpack into
     int myInt, myInt1;
     string myString, myString1;
     int[] myArray, myArray1;

     // Use AliasSeq to unpack the tuple
     AliasSeq!(myInt1, myString1, myArray1) = myTuple1;

     // Now the variables contain the tuple contents
     writeln(myInt1); // 42
     writeln(myString1); // "bye"
     writeln(myArray1); // [3, 4]

     // using an alias to make more descriptive & possibly shorter
     alias unpack = AliasSeq;
     unpack!(myInt, myString, myArray) = myTuple;

     // Now the variables contain the tuple contents
     writeln(myInt); // 10
     writeln(myString); // "hello"
     writeln(myArray); // [1, 2]

     // Can also unpack directly:
     writeln(myTuple[0]); // 10

}
```
I really didn't know AliasSeq!, so I had Claude2 explain it to 
me. Perhaps the explanation below will help other newbies:

---

The `AliasSeq!(myInt, myString, myArray) = myTuple;` line is 
using AliasSeq to unpack the tuple into the individual variables. 
Here is what happens in more detail:

1. AliasSeq takes a list of symbols as template arguments - in 
this case the variables we declared before (myInt, myString, 
myArray)

2. It generates aliases to match each tuple element to the 
variables passed in.
    So the first alias will refer to myTuple[0], the second to 
myTuple[1], etc.

3. The assignment then takes the value on the right (myTuple) and 
copies each tuple element over to the variable the alias refers 
to.

So for example, something like this is generated internally:

```d
__alias1 = myTuple[0]; // alias for first element
__alias2 = myTuple[1]; // alias for second element

// Assign aliases to variables
myInt = __alias1;
myString = __alias2;
myArray = __alias3;
```

The key thing AliasSeq does behind the scenes is generate those 
positional aliases to each tuple element, and match them up to 
the variables we want to unpack into.

The assignment then copies the tuple elements over using the 
aliases.



More information about the Digitalmars-d-learn mailing list