summaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
-rw-r--r--exercises/047_methods.zig43
1 files changed, 24 insertions, 19 deletions
diff --git a/exercises/047_methods.zig b/exercises/047_methods.zig
index 96d4c8e..7211caa 100644
--- a/exercises/047_methods.zig
+++ b/exercises/047_methods.zig
@@ -2,9 +2,9 @@
// Help! Evil alien creatures have hidden eggs all over the Earth
// and they're starting to hatch!
//
-// Before you jump into battle, you'll need to know four things:
+// Before you jump into battle, you'll need to know three things:
//
-// 1. You can attach functions to structs:
+// 1. You can attach functions to structs (and other "type definitions"):
//
// const Foo = struct{
// pub fn hello() void {
@@ -12,31 +12,34 @@
// }
// };
//
-// 2. A function that is a member of a struct is a "method" and is
-// called with the "dot syntax" like so:
+// 2. A function that is a member of a struct is "namespaced" within
+// that struct and is called by specifying the "namespace" and then
+// using the "dot syntax":
//
// Foo.hello();
//
-// 3. The NEAT feature of methods is the special parameter named
-// "self" that takes an instance of that type of struct:
+// 3. The NEAT feature of these functions is that if they take either
+// an instance of the struct or a pointer to an instance of the struct
+// then they have some syntax sugar:
//
// const Bar = struct{
-// number: u32,
-//
-// pub fn printMe(self: Bar) void {
-// std.debug.print("{}\n", .{self.number});
-// }
+// pub fn a(self: Bar) void { _ = self; }
+// pub fn b(this: *Bar, other: u8) void { _ = this; _ = other; }
+// pub fn c(bar: *const Bar) void { _ = bar; }
// };
//
-// (Actually, you can name the first parameter anything, but
-// please follow convention and use "self".)
+// var bar = Bar{};
+// bar.a() // is equivalent to Bar.a(bar)
+// bar.b(3) // is equivalent to Bar.b(&bar, 3)
+// bar.c() // is equivalent to Bar.c(&bar)
//
-// 4. Now when you call the method on an INSTANCE of that struct
-// with the "dot syntax", the instance will be automatically
-// passed as the "self" parameter:
+// Notice that the name of the parameter doesn't matter. Some use
+// self, others use a lowercase version of the type name, but feel
+// free to use whatever is most appropriate.
//
-// var my_bar = Bar{ .number = 2000 };
-// my_bar.printMe(); // prints "2000"
+// Effectively, the method syntax sugar just does this transformation:
+// thing.function(args);
+// @TypeOf(thing).function(thing, args);
//
// Okay, you're armed.
//
@@ -63,7 +66,9 @@ const HeatRay = struct {
// We love this method:
pub fn zap(self: HeatRay, alien: *Alien) void {
- alien.health -= if (self.damage >= alien.health) alien.health else self.damage;
+ alien.health -|= self.damage; // Saturating inplace substraction
+ // It subtracts but doesn't go below the
+ // lowest value for our type (in this case 0)
}
};