aboutsummaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
authorDave Gauer <ratfactor@gmail.com>2023-05-04 08:25:28 -0400
committerGitHub <noreply@github.com>2023-05-04 08:25:28 -0400
commit7a44e4d3426e6db2bbb7822563a1372fc22a1025 (patch)
treef4a93bca42647e895a70e68b635f781d1c4a2abf
parent8345197f54e6725b4d2926ca4cfe620beb95200c (diff)
parent3612c67f04e0d902a12c3f71ed52b1de8422804e (diff)
Merge pull request #265 from Arya-Elfren/methods-clarification
Clarify the methods syntax sugar & a bit more
-rw-r--r--exercises/047_methods.zig37
1 files changed, 18 insertions, 19 deletions
diff --git a/exercises/047_methods.zig b/exercises/047_methods.zig
index 96d4c8e..6b2dbef 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,30 @@
// }
// };
//
-// 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 their first argument
+// is an instance of the struct (or a pointer to one) then we can use
+// the instance as the namespace instead of the type:
//
// const Bar = struct{
-// number: u32,
-//
-// pub fn printMe(self: Bar) void {
-// std.debug.print("{}\n", .{self.number});
-// }
+// pub fn a(self: Bar) void {}
+// pub fn b(this: *Bar, other: u8) void {}
+// pub fn c(bar: *const Bar) void {}
// };
//
-// (Actually, you can name the first parameter anything, but
-// please follow convention and use "self".)
-//
-// 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:
+// 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)
//
-// var my_bar = Bar{ .number = 2000 };
-// my_bar.printMe(); // prints "2000"
+// 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.
//
// Okay, you're armed.
//