Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What principle difference between Structure and Tuple?

Tags:

d

writeln(is(Tuple!(string, int) == struct)); // true

What is real user case when I should use Tuple instead of struct?

like image 417
Dmitry Bubnenkov Avatar asked Jan 03 '23 16:01

Dmitry Bubnenkov


1 Answers

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).

like image 163
greenify Avatar answered Jan 09 '23 06:01

greenify