如何初始化并返回内联结构?

时间:2013-11-13 20:21:43

标签: syntax struct return d

我想初始化一个结构并将其返回到Digitalmars D的同一行。我该怎么做?

struct Record {
    immutable(ubyte) protocolVersion;
    immutable(ubyte) type;
    immutable(ushort) requestId;
}

class test {
    Record nextRequest() {
        ubyte buffer[512];
        auto bytesReceived = socketIn.receive(buffer);
        if(bytesReceived < 0)
            throw new ErrnoException("Error while receiving data");
        else if(bytesReceived == 0)
            throw new ConnectionClosedException();

        return {
            protocolVersion:1, //52
            type:1, //53
            requestId:1 //54
        }; //55
    } //56
} // 57

此代码给出了编译错误:

file.d(53): Error: found ':' when expecting ';' following statement
file.d(54): Error: found ':' when expecting ';' following statement
file.d(55): Error: expression expected, not '}'
file.d(56): Error: found '}' when expecting ';' following return statement

2 个答案:

答案 0 :(得分:7)

C style {}语法仅在顶部声明

中可用
SomeStruct c = { foo, bar, etc}; // ok

但是像你一样返回它将无法工作 - 在其他情况下,{stuff}意味着函数文字。

return {
    writeln("cool");
};

例如,将尝试返回void函数(),您将看到类型不匹配。

最适合D的方法是使用构造函数样式语法。它不会做命名成员,但可以在任何地方工作:

return Record(1, 1, 1);

每个参数都填充了结构的一个成员。因此Record(1,2,3)将protocolVersion设置为1,type为2,requestId设置为3。

您还可以定义结构构造函数来自定义此行为,语法为this(int arg, int arg2) { currentVersion = arg; /* and whatever else */ }但如果您只想填写所有成员,则不必定义构造函数。 return Record(1,1,1);将使用您的代码。

答案 1 :(得分:5)

到目前为止最简单的方法是简单地调用默认构造函数。

return Record(1, 1, 1);
相关问题