module test;
import std.stdio;
struct Result(T)
{
@property static ref Result!T fail(int errorCode)
{
static Result!T result;
result.errorCode = errorCode;
return result;
}
@property ref Result!T ok(T init)
{
errorCode = 0;
__hiddenMember = init;
return this;
}
int errorCode = -1;
auto opCast(T = bool)() { return errorCode == 0; }
T __hiddenMember;
alias __hiddenMember this;
}
struct Coords { int x, y, z; }
Result!Coords getCoords(bool isTrue)
{
typeof(return) result;
if (isTrue)
return result.ok(Coords(1, 2, 3));
else
return result.fail(-4);
}
void main()
{
Coords coords1 = getCoords(true);
assert(coords1 == Coords(1, 2, 3));
auto result = getCoords(false);
if (!result) // calls opCast!bool
writefln("Error code: %s", result.errorCode);
else
coords1 = result; // uses 'alias this' to assign the field
Coords coords2;
auto status2 = getCoords(true);
if (status2) // calls opCast!bool
coords2 = status2; // uses 'alias this' to assign the field
assert(coords2 == Coords(1, 2, 3));
Coords coords3;
if (auto status3 = getCoords(true)) // calls opCast!bool, and if true returns 'Result!Coords' struct
coords3 = status3; // uses 'alias this' to assign the field
assert(coords3 == Coords(1, 2, 3));
}
bW9kdWxlIHRlc3Q7CgppbXBvcnQgc3RkLnN0ZGlvOwoKc3RydWN0IFJlc3VsdChUKSAKewogICAgQHByb3BlcnR5IHN0YXRpYyByZWYgUmVzdWx0IVQgZmFpbChpbnQgZXJyb3JDb2RlKSAKICAgIHsgCiAgICAgICAgc3RhdGljIFJlc3VsdCFUIHJlc3VsdDsKICAgICAgICByZXN1bHQuZXJyb3JDb2RlID0gZXJyb3JDb2RlOwogICAgICAgIHJldHVybiByZXN1bHQ7CiAgICB9ICAgIAogICAgCiAgICBAcHJvcGVydHkgcmVmIFJlc3VsdCFUIG9rKFQgaW5pdCkgCiAgICB7CiAgICAgICAgZXJyb3JDb2RlID0gMDsKICAgICAgICBfX2hpZGRlbk1lbWJlciA9IGluaXQ7CiAgICAgICAgcmV0dXJuIHRoaXM7CiAgICB9CgogICAgaW50IGVycm9yQ29kZSA9IC0xOwogICAgYXV0byBvcENhc3QoV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