What is the fundamental difference between a structure and a tuple?

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

What is the real case of the user when I should use Tupleinstead struct?

+4
source share
2 answers

Tuplemainly for convenience, since it often shortens the record tuple(0, "bar")than defining a structure.

There are several uses for tuples, for example. unpacking on AliasSeq:

import std.typecons : tuple;

void bar(int i, string s) {}

void main()
{
    auto t = tuple(1, "s");
    bar(t.expand);
}

expand It can also be convenient 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 case is zipwhere the result zip([0], ["s"])is Tuple!(int, string)(or in general staticMap!(ElementType, Args)), which is easier than generating the structure dynamically (although, of course, with static foreachor mixinthis is also possible).

+6
source

, .

.

, Tuple (/ ) , Struct , . .. Tuple!(string,int), , , int tuple ; (, Struct fun(arg)), int (struct Struct{string s; int i;}), , , .

, Vector Position (struct Pos {int x; int y;} vs int[2])

Tuple!(string,int) == Tuple!(string,int) StructA != StructB

, /.

+3

Source: https://habr.com/ru/post/1694755/


All Articles