038_structs2.zig 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // Zump the Loud
  32. chars[1] = Character{
  33. .role = Role.bard,
  34. .gold = 10,
  35. .health = 100,
  36. .experience = 20,
  37. };
  38. // Please add "Zump the Loud" with the following properties:
  39. //
  40. // role bard
  41. // gold 10
  42. // health 100
  43. // experience 20
  44. //
  45. // Feel free to run this program without adding Zump. What does
  46. // it do and why?
  47. // Printing all RPG characters in a loop:
  48. for(chars, 0..) |c, num|{
  49. std.debug.print("Character {} - G:{} H:{} XP:{}\n", .{
  50. num + 1, c.gold, c.health, c.experience,
  51. });
  52. }
  53. }
  54. // If you tried running the program without adding Zump as mentioned
  55. // above, you get what appear to be "garbage" values. In debug mode
  56. // (which is the default), Zig writes the repeating pattern "10101010"
  57. // in binary (or 0xAA in hex) to all undefined locations to make them
  58. // easier to spot when debugging.