031_switch2.zig 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //
  2. // What's really nice is that you can use a switch statement as an
  3. // expression to return a value.
  4. //
  5. // var a = switch (x) {
  6. // 1 => 9,
  7. // 2 => 16,
  8. // 3 => 7,
  9. // ...
  10. // }
  11. //
  12. const std = @import("std");
  13. pub fn main() void {
  14. const lang_chars = [_]u8{ 26, 9, 7, 42 };
  15. for (lang_chars) |c| {
  16. var real_char: u8 = switch (c) {
  17. 1 => 'A',
  18. 2 => 'B',
  19. 3 => 'C',
  20. 4 => 'D',
  21. 5 => 'E',
  22. 6 => 'F',
  23. 7 => 'G',
  24. 8 => 'H',
  25. 9 => 'I',
  26. 10 => 'J',
  27. // ...
  28. 25 => 'Y',
  29. 26 => 'Z',
  30. // As in the last exercise, please add the "else" clause
  31. // and this time, have it return an exclamation mark "!".
  32. };
  33. std.debug.print("{c}", .{real_char});
  34. // Note: "{c}" forces print() to display the value as a character.
  35. // Can you guess what happens if you remove the "c"? Try it!
  36. }
  37. std.debug.print("\n", .{});
  38. }