047_methods.zig 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // Help! Evil alien creatures have hidden eggs all over the Earth
  3. // and they're starting to hatch!
  4. //
  5. // Before you jump into battle, you'll need to know four things:
  6. //
  7. // 1. You can attach functions to structs:
  8. //
  9. // const Foo = struct{
  10. // pub fn hello() void {
  11. // std.debug.print("Foo says hello!\n", .{});
  12. // }
  13. // }
  14. //
  15. // 2. A function that is a member of a struct is a "method" and is
  16. // called with the "dot syntax" like so:
  17. //
  18. // Foo.hello();
  19. //
  20. // 3. The NEAT feature of methods is the special parameter named
  21. // "self" that takes an instance of that type of struct:
  22. //
  23. // const Bar = struct{
  24. // number: u32,
  25. //
  26. // pub fn printMe(self: *Bar) void {
  27. // std.debug.print("{}\n", .{self.number});
  28. // }
  29. // }
  30. //
  31. // 4. Now when you call the method on an INSTANCE of that struct
  32. // with the "dot syntax", the instance will be automatically
  33. // passed as the "self" parameter:
  34. //
  35. // var my_bar = Bar{ .number = 2000 };
  36. // my_bar.printMe(); // prints "2000"
  37. //
  38. // Okay, you're armed.
  39. //
  40. // Now, please zap the alien structs until they're all gone or
  41. // Earth will be doomed!
  42. //
  43. const std = @import("std");
  44. // Look at this hideous Alien struct. Know your enemy!
  45. const Alien = struct {
  46. health: u8,
  47. // We hate this method:
  48. pub fn hatch(strength: u8) Alien {
  49. return Alien{
  50. .health = strength * 5,
  51. };
  52. }
  53. // We love this method:
  54. pub fn zap(self: *Alien, damage: u8) void {
  55. self.health -= if (damage >= self.health) self.health else damage;
  56. }
  57. };
  58. pub fn main() void {
  59. // Look at all of these aliens of various strengths!
  60. var aliens = [_]Alien{
  61. Alien.hatch(2),
  62. Alien.hatch(1),
  63. Alien.hatch(3),
  64. Alien.hatch(3),
  65. Alien.hatch(5),
  66. Alien.hatch(3),
  67. };
  68. var aliens_alive = aliens.len;
  69. var heat_ray_strength: u8 = 7; // We've been given a heat ray weapon.
  70. // We'll keep checking to see if we've killed all the aliens yet.
  71. while (aliens_alive > 0) {
  72. aliens_alive = 0;
  73. // Loop through every alien...
  74. for (aliens) |*alien| {
  75. // *** Zap the Alien Here! ***
  76. ???.zap(heat_ray_strength);
  77. // If the alien's health is still above 0, it's still alive.
  78. if (alien.health > 0) aliens_alive += 1;
  79. }
  80. std.debug.print("{} aliens. ", .{aliens_alive});
  81. }
  82. std.debug.print("Earth is saved!\n", .{});
  83. }