if

if.zig

  1. // If expressions have three uses, corresponding to the three types:
  2. // * bool
  3. // * ?T
  4. // * anyerror!T
  5. const assert = @import("std").debug.assert;
  6. test "if boolean" {
  7. // If expressions test boolean conditions.
  8. const a: u32 = 5;
  9. const b: u32 = 4;
  10. if (a != b) {
  11. assert(true);
  12. } else if (a == 9) {
  13. unreachable;
  14. } else {
  15. unreachable;
  16. }
  17. // If expressions are used instead of a ternary expression.
  18. const result = if (a != b) 47 else 3089;
  19. assert(result == 47);
  20. }
  21. test "if optional" {
  22. // If expressions test for null.
  23. const a: ?u32 = 0;
  24. if (a) |value| {
  25. assert(value == 0);
  26. } else {
  27. unreachable;
  28. }
  29. const b: ?u32 = null;
  30. if (b) |value| {
  31. unreachable;
  32. } else {
  33. assert(true);
  34. }
  35. // The else is not required.
  36. if (a) |value| {
  37. assert(value == 0);
  38. }
  39. // To test against null only, use the binary equality operator.
  40. if (b == null) {
  41. assert(true);
  42. }
  43. // Access the value by reference using a pointer capture.
  44. var c: ?u32 = 3;
  45. if (c) |*value| {
  46. value.* = 2;
  47. }
  48. if (c) |value| {
  49. assert(value == 2);
  50. } else {
  51. unreachable;
  52. }
  53. }
  54. test "if error union" {
  55. // If expressions test for errors.
  56. // Note the |err| capture on the else.
  57. const a: anyerror!u32 = 0;
  58. if (a) |value| {
  59. assert(value == 0);
  60. } else |err| {
  61. unreachable;
  62. }
  63. const b: anyerror!u32 = error.BadValue;
  64. if (b) |value| {
  65. unreachable;
  66. } else |err| {
  67. assert(err == error.BadValue);
  68. }
  69. // The else and |err| capture is strictly required.
  70. if (a) |value| {
  71. assert(value == 0);
  72. } else |_| {}
  73. // To check only the error value, use an empty block expression.
  74. if (b) |_| {} else |err| {
  75. assert(err == error.BadValue);
  76. }
  77. // Access the value by reference using a pointer capture.
  78. var c: anyerror!u32 = 3;
  79. if (c) |*value| {
  80. value.* = 9;
  81. } else |err| {
  82. unreachable;
  83. }
  84. if (c) |value| {
  85. assert(value == 9);
  86. } else |err| {
  87. unreachable;
  88. }
  89. }
  1. $ zig test if.zig
  2. 1/3 test "if boolean"...OK
  3. 2/3 test "if optional"...OK
  4. 3/3 test "if error union"...OK
  5. All tests passed.

See also: