30_switch.zig 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // The "switch" statement lets you match the possible values of an
  3. // expression and perform a different action for each.
  4. //
  5. // This switch:
  6. //
  7. // switch (players) {
  8. // 1 => startOnePlayerGame(),
  9. // 2 => startTwoPlayerGame(),
  10. // else => {
  11. // alert();
  12. // return GameError.TooManyPlayers;
  13. // }
  14. // }
  15. //
  16. // Is equivalent to this if/else:
  17. //
  18. // if (players == 1) startOnePlayerGame();
  19. // else if (players == 2) startTwoPlayerGame();
  20. // else {
  21. // alert();
  22. // return GameError.TooManyPlayers;
  23. // }
  24. //
  25. //
  26. //
  27. const std = @import("std");
  28. pub fn main() void {
  29. const lang_chars = [_]u8{ 26, 9, 7, 42 };
  30. for (lang_chars) |c| {
  31. switch (c) {
  32. 1 => std.debug.print("A", .{}),
  33. 2 => std.debug.print("B", .{}),
  34. 3 => std.debug.print("C", .{}),
  35. 4 => std.debug.print("D", .{}),
  36. 5 => std.debug.print("E", .{}),
  37. 6 => std.debug.print("F", .{}),
  38. 7 => std.debug.print("G", .{}),
  39. 8 => std.debug.print("H", .{}),
  40. 9 => std.debug.print("I", .{}),
  41. 10 => std.debug.print("J", .{}),
  42. // ... we don't need everything in between ...
  43. 25 => std.debug.print("Y", .{}),
  44. 26 => std.debug.print("Z", .{}),
  45. // Switch statements must be "exhaustive" (there must be a
  46. // match for every possible value). Please add an "else"
  47. // to this switch to print a question mark "?" when c is
  48. // not one of the existing matches.
  49. }
  50. }
  51. std.debug.print("\n", .{});
  52. }