037_structs.zig 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // Being able to group values together lets us turn this:
  3. //
  4. // point1_x = 3;
  5. // point1_y = 16;
  6. // point1_z = 27;
  7. // point2_x = 7;
  8. // point2_y = 13;
  9. // point2_z = 34;
  10. //
  11. // into this:
  12. //
  13. // point1 = Point{ .x=3, .y=16, .z=27 };
  14. // point2 = Point{ .x=7, .y=13, .z=34 };
  15. //
  16. // The Point above is an example of a "struct" (short for "structure").
  17. // Here's how that struct type could have been defined:
  18. //
  19. // const Point = struct{ x: u32, y: u32, z: u32 };
  20. //
  21. // Let's store something fun with a struct: a roleplaying character!
  22. //
  23. const std = @import("std");
  24. // We'll use an enum to specify the character role.
  25. const Role = enum{
  26. wizard,
  27. thief,
  28. bard,
  29. warrior,
  30. };
  31. // Please add a new property to this struct called "health" and make
  32. // it a u8 integer type.
  33. const Character = struct{
  34. role: Role,
  35. gold: u32,
  36. experience: u32,
  37. health: u8,
  38. };
  39. pub fn main() void{
  40. // Please initialize Glorp with 100 health.
  41. var glorp_the_wise = Character{
  42. .role = Role.wizard,
  43. .gold = 20,
  44. .experience = 10,
  45. .health = 100
  46. };
  47. // Glorp gains some gold.
  48. glorp_the_wise.gold += 5;
  49. // Ouch! Glorp takes a punch!
  50. glorp_the_wise.health -= 10;
  51. std.debug.print("Your wizard has {} health and {} gold.\n", .{
  52. glorp_the_wise.health,
  53. glorp_the_wise.gold,
  54. });
  55. }