Reputation: 9859
writeln(is(Tuple!(string, int) == struct)); // true
What is real user case when I should use Tuple
instead of struct
?
Upvotes: 4
Views: 425
Reputation: 459
Largely choosing one over the other is based on preference, some coder may never use Tuples and other most of the time.
They do generally have different use cases.
The primary difference is that a Tuple is typed (named/identified by the compiler) by the types in it while a Struct is typed by a label chosen by the coder. i.e. if a function returns Tuple!(string,int)
and another function that returns a string and int tuple will be returning the same type; but if a function returns a struct (e.g. Struct fun(arg)
) that contains a string and int (struct Struct{string s; int i;}
) it can be returning a different type than another function that returns a different struct with the same types.
Essentially the same difference and reasons a coder would choose a struct or an array for Vector or Position (struct Pos {int x; int y;}
vs int[2]
)
Tuple!(string,int) == Tuple!(string,int)
StructA != StructB
No hard rule just how strongly typed you want to / is appropriate to be.
Upvotes: 3
Reputation: 1127
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).
Upvotes: 6