038_structs2.zig 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // Grouping values in structs is not merely convenient. It also allows
  3. // us to treat the values as a single item when storing them, passing
  4. // them to functions, etc.
  5. //
  6. // This exercise demonstrates how we can store structs in an array and
  7. // how doing so lets us print them using a loop.
  8. //
  9. const std = @import("std");
  10. const Role = enum {
  11. wizard,
  12. thief,
  13. bard,
  14. warrior,
  15. };
  16. const Character = struct {
  17. role: Role,
  18. gold: u32,
  19. health: u8,
  20. experience: u32,
  21. };
  22. pub fn main() void {
  23. var chars: [2]Character = undefined;
  24. // Glorp the Wise
  25. chars[0] = Character{
  26. .role = Role.wizard,
  27. .gold = 20,
  28. .health = 100,
  29. .experience = 10,
  30. };
  31. // Please add "Zump the Loud" with the following properties:
  32. //
  33. // role bard
  34. // gold 10
  35. // health 100
  36. // experience 20
  37. //
  38. // Feel free to run this program without adding Zump. What does
  39. // it do and why?
  40. // Printing all RPG characters in a loop:
  41. for (chars, 0..) |c, num| {
  42. std.debug.print("Character {} - G:{} H:{} XP:{}\n", .{
  43. num + 1, c.gold, c.health, c.experience,
  44. });
  45. }
  46. }
  47. // If you tried running the program without adding Zump as mentioned
  48. // above, you get what appear to be "garbage" values. In debug mode
  49. // (which is the default), Zig writes the repeating pattern "10101010"
  50. // in binary (or 0xAA in hex) to all undefined locations to make them
  51. // easier to spot when debugging.