D 使用writeln打印结构时额外为null

D 使用writeln打印结构时额外为null,d,D,在下面的代码中,当使用writeln打印S2的实例时,输出中额外的null是什么 $ dmd -de -w so_004.d && ./so_004 S1("A", 1) S2("A", 1, null) 如果我在包范围内定义S2(即main函数之外),则null将消失 使用合理的最新DMD进行编译: $ dmd --version DMD64 D Compiler v2.083.0 Copyright (C) 1999-2018 by The D Language Found

在下面的代码中,当使用
writeln
打印
S2
的实例时,输出中额外的
null
是什么

$ dmd -de -w so_004.d && ./so_004
S1("A", 1)
S2("A", 1, null)
如果我在包范围内定义
S2
(即
main
函数之外),则
null
将消失

使用合理的最新DMD进行编译:

$ dmd --version
DMD64 D Compiler v2.083.0
Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved written by Walter Bright
我在学习
opEquals
时注意到了这个问题,我不打算在“real”代码的子范围中定义类型

它是上下文指针(在
S2.tupleof
中称为
this
),指的是创建
S2
实例的堆栈框架。这通常会在如下代码中使用:

auto fun(int n) {
    struct S {
        int get() { return n; }
    }
    return S();
}
上面的代码将在堆上分配
n
,并将指向它的指针放在
S
这个
成员中

现在,至于为什么它在你的代码中-。不需要上下文指针,因为结构没有使用其作用域中的任何变量。要删除它,只需将
S2
标记为
static

static struct S2 {
    string id; ushort x;
    bool opEquals()(auto ref const string rhs) const {
        return id == rhs;
    }
}

auto a = S2("A", 1);
writeln(a); // S2("A", 1)
static struct S2 {
    string id; ushort x;
    bool opEquals()(auto ref const string rhs) const {
        return id == rhs;
    }
}

auto a = S2("A", 1);
writeln(a); // S2("A", 1)