28_defer2.zig 836 B

1234567891011121314151617181920212223242526272829
  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'){ std.debug.print("Goat", .{}); return; }
  18. if (animal == 'c'){ std.debug.print("Cat", .{}); return; }
  19. if (animal == 'd'){ std.debug.print("Dog", .{}); return; }
  20. std.debug.print("Unknown", .{});
  21. }