结构和元组有什么主要区别?

Dmi*_*kov 4 d

writeln(is(Tuple!(string, int) == struct)); // true
Run Code Online (Sandbox Code Playgroud)

什么是真正的用户案例,我应该使用Tuple而不是struct

gre*_*ify 6

Tuple主要是为了方便,因为它tuple(0, "bar")比定义结构通常更短.

有一些使用情况,元组很方便,例如解包到AliasSeq:

import std.typecons : tuple;

void bar(int i, string s) {}

void main()
{
    auto t = tuple(1, "s");
    bar(t.expand);
}
Run Code Online (Sandbox Code Playgroud)

expand 使用范围时也可以很方便:

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
}
Run Code Online (Sandbox Code Playgroud)

另一个实际的使用情况是zip,其中的结果zip([0], ["s"])Tuple!(int, string)(或一般staticMap!(ElementType, Args)),这是比动态地生成结构(当然,使用更加简单static foreachmixin这将是可能太).