writeln(is(Tuple!(string, int) == struct)); // true
What is real user case when I should use Tuple
instead of struct
?
Tuple
is mostly for convenience as it's often shorter to write tuple(0, "bar")
than defining the struct.
There are a few use cases where a tuple is handy, e.g. unwrapping to an AliasSeq
:
import std.typecons : tuple;
void bar(int i, string s) {}
void main()
{
auto t = tuple(1, "s");
bar(t.expand);
}
expand
can also be handy when working with ranges:
void main()
{
import std.stdio : writeln;
import std.typecons : tuple;
auto ts = tuple(1, "s");
foreach (t; ts)
{
t.writeln;
}
import std.algorithm : minElement;
import std.range;
tuple(2, 1, 3).expand.only.minElement.writeln; // 1
}
Another real-use case is zip
where the result of zip([0], ["s"])
is Tuple!(int, string)
(or in general staticMap!(ElementType, Args)
) which is easier than generating the struct dynamically (though of course with static foreach
or mixin
that would be possible too).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With