fork download
  1. module test;
  2.  
  3. import std.stdio;
  4.  
  5. struct Result(T)
  6. {
  7. @property static ref Result!T fail(int errorCode)
  8. {
  9. static Result!T result;
  10. result.errorCode = errorCode;
  11. return result;
  12. }
  13.  
  14. @property ref Result!T ok(T init)
  15. {
  16. errorCode = 0;
  17. __hiddenMember = init;
  18. return this;
  19. }
  20.  
  21. int errorCode = -1;
  22. auto opCast(T = bool)() { return errorCode == 0; }
  23. T __hiddenMember;
  24. alias __hiddenMember this;
  25. }
  26.  
  27. struct Coords { int x, y, z; }
  28.  
  29. Result!Coords getCoords(bool isTrue)
  30. {
  31. typeof(return) result;
  32.  
  33. if (isTrue)
  34. return result.ok(Coords(1, 2, 3));
  35. else
  36. return result.fail(-4);
  37. }
  38.  
  39. void main()
  40. {
  41. Coords coords1 = getCoords(true);
  42. assert(coords1 == Coords(1, 2, 3));
  43.  
  44. auto result = getCoords(false);
  45. if (!result) // calls opCast!bool
  46. writefln("Error code: %s", result.errorCode);
  47. else
  48. coords1 = result; // uses 'alias this' to assign the field
  49.  
  50. Coords coords2;
  51. auto status2 = getCoords(true);
  52. if (status2) // calls opCast!bool
  53. coords2 = status2; // uses 'alias this' to assign the field
  54. assert(coords2 == Coords(1, 2, 3));
  55.  
  56. Coords coords3;
  57. if (auto status3 = getCoords(true)) // calls opCast!bool, and if true returns 'Result!Coords' struct
  58. coords3 = status3; // uses 'alias this' to assign the field
  59. assert(coords3 == Coords(1, 2, 3));
  60. }
  61.  
  62.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty