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

Jer*_*oen 1 syntax struct d return

我想初始化一个结构并将其返回到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
Run Code Online (Sandbox Code Playgroud)

这段代码给了我编译错误:

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

Ada*_*ppe 7

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

SomeStruct c = { foo, bar, etc}; // ok
Run Code Online (Sandbox Code Playgroud)

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

return {
    writeln("cool");
};
Run Code Online (Sandbox Code Playgroud)

例如,将尝试返回void function(),您将看到类型不匹配.

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

return Record(1, 1, 1);
Run Code Online (Sandbox Code Playgroud)

那里的每个参数都填充了结构的一个成员.因此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);将尽可能使用您的代码.


Orv*_*ing 5

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

return Record(1, 1, 1);
Run Code Online (Sandbox Code Playgroud)