028_defer2.zig 894 B

12345678910111213141516171819202122232425262728293031323334353637
  1. //
  2. // Now that you know how "defer" works, let's do something more
  3. // interesting with it.
  4. //
  5. const std = @import("std");
  6. pub fn main() void {
  7. const animals = [_]u8{ 'g', 'c', 'd', 'd', 'g', 'z' };
  8. for (animals) |a| printAnimal(a);
  9. std.debug.print("done.\n", .{});
  10. }
  11. // This function is _supposed_ to print an animal name in parentheses
  12. // like "(Goat) ", but we somehow need to print the end parenthesis
  13. // even though this function can return in four different places!
  14. fn printAnimal(animal: u8) void {
  15. std.debug.print("(", .{});
  16. std.debug.print(") ", .{}); // <---- how!?
  17. if (animal == 'g') {
  18. std.debug.print("Goat", .{});
  19. return;
  20. }
  21. if (animal == 'c') {
  22. std.debug.print("Cat", .{});
  23. return;
  24. }
  25. if (animal == 'd') {
  26. std.debug.print("Dog", .{});
  27. return;
  28. }
  29. std.debug.print("Unknown", .{});
  30. }