aboutsummaryrefslogtreecommitdiff
path: root/exercises/045_optionals.zig
diff options
context:
space:
mode:
authorDave Gauer <dave@ratfactor.com>2021-03-12 18:59:46 -0500
committerDave Gauer <dave@ratfactor.com>2021-03-12 18:59:46 -0500
commit6ad9774189fbd64b2f2c9519f4513ab34b0c3809 (patch)
treed6c90700131d5b28e898881f13e2a05612e4703f /exercises/045_optionals.zig
parentbe36352572ddb18218e1830e49316c259dea5e8c (diff)
downloadziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.gz
ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.bz2
ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.tar.xz
ziglings-6ad9774189fbd64b2f2c9519f4513ab34b0c3809.zip
"999 is enough for anybody" triple-zero padding (#18)
When I hit 999 exercises, I will finally have reached the ultimate state of soteriological release and no more exercises will be needed. The cycle will be complete. All that will be left is perfect quietude, freedom, and highest happiness.
Diffstat (limited to 'exercises/045_optionals.zig')
-rw-r--r--exercises/045_optionals.zig51
1 files changed, 51 insertions, 0 deletions
diff --git a/exercises/045_optionals.zig b/exercises/045_optionals.zig
new file mode 100644
index 0000000..1327e4c
--- /dev/null
+++ b/exercises/045_optionals.zig
@@ -0,0 +1,51 @@
+//
+// Sometimes you know that a variable might hold a value or
+// it might not. Zig has a neat way of expressing this idea
+// called Optionals. An optional type just has a '?' like this:
+//
+// var foo: ?u32 = 10;
+//
+// Now foo can store a u32 integer OR null (a value storing
+// the cosmic horror of a value NOT EXISTING!)
+//
+// foo = null;
+//
+// if (foo == null) beginScreaming();
+//
+// Before we can use the optional value as the non-null type
+// (a u32 integer in this case), we need to guarantee that it
+// isn't null. One way to do this is to THREATEN IT with the
+// "orelse" statement.
+//
+// var bar = foo orelse 2;
+//
+// Here, bar will either equal the u32 integer value stored in
+// foo, or it will equal 2 if foo was null.
+//
+const std = @import("std");
+
+pub fn main() void {
+ const result = deepThought();
+
+ // Please threaten the result so that answer is either the
+ // integer value from deepThought() OR the number 42:
+ var answer: u8 = result;
+
+ std.debug.print("The Ultimate Answer: {}.\n", .{answer});
+}
+
+fn deepThought() ?u8 {
+ // It seems Deep Thought's output has declined in quality.
+ // But we'll leave this as-is. Sorry Deep Thought.
+ return null;
+}
+// Blast from the past:
+//
+// Optionals are a lot like error union types which can either
+// hold a value or an error. Likewise, the orelse statement is
+// like the catch statement used to "unwrap" a value or supply
+// a default value:
+//
+// var maybe_bad: Error!u32 = Error.Evil;
+// var number: u32 = maybe_bad catch 0;
+//