diff options
author | Dave Gauer <dave@ratfactor.com> | 2021-02-08 20:35:28 -0500 |
---|---|---|
committer | Dave Gauer <dave@ratfactor.com> | 2021-02-08 20:35:28 -0500 |
commit | cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907 (patch) | |
tree | d0c1af19e12e503a6d720b8e8ef487966e4c7d75 /43_pointers5.zig | |
parent | adf5ddb27df7f5a22b0b7d3321dfc8bca1e7937a (diff) | |
download | ziglings-cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907.tar.gz ziglings-cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907.tar.bz2 ziglings-cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907.tar.xz ziglings-cf0920de31e9b5f3c5ba6de19a1b4c8d0c58b907.zip |
Added Ex. 38-43 for pointers, updated README
Added topics beyond the language basics from ziglearn.org
to the README. That's a lot of exercises. I'd like to keep
it under 100, though!
Diffstat (limited to '43_pointers5.zig')
-rw-r--r-- | 43_pointers5.zig | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/43_pointers5.zig b/43_pointers5.zig new file mode 100644 index 0000000..adfaea1 --- /dev/null +++ b/43_pointers5.zig @@ -0,0 +1,84 @@ +// +// Passing integer pointers around is generally not something you're going +// to do. Integers are cheap to copy. +// +// But you know what IS useful? Pointers to structs: +// +// const Vertex = struct{ x: u32, y: u32, z: u32 }; +// +// var v1 = Vertex{ .x=3, .y=2, .z=5 }; +// +// var pv: *Vertex = &v1; // <-- a pointer to our struct +// +// Note that you don't need to dereference the "pv" pointer to access +// the struct's fields: +// +// YES: pv.x +// NO: pv.*.x +// +// We can write functions that take pointer arguments: +// +// fn foo(v: *Vertex) void { +// v.x += 2; +// v.y += 3; +// v.z += 7; +// } +// +// And pass references to them: +// +// foo(&v1); +// +// +// Let's revisit our RPG example and make a printCharacter() function +// that takes a Character pointer. +// +const std = @import("std"); + +const Class = enum{ + wizard, + thief, + bard, + warrior, +}; + +const Character = struct{ + class: Class, + gold: u32, + health: u8, + experience: u32, +}; + +pub fn main() void { + var glorp = Character{ + .class = Class.wizard, + .gold = 10, + .health = 100, + .experience = 20, + }; + + // FIX ME! + // Please pass our Character "glorp" to printCharacter(): + printCharacter( ??? ); +} + + +// Note how this function's "c" parameter is a pointer to a Character struct. +fn printCharacter(c: *Character) void { + + // Here's something you haven't seen before: when switching an enum, you + // don't have to write the full enum name. Zig understands that ".wizard" + // means "Class.wizard" when we switch on a Class enum value: + const class_name = switch (c.class) { + .wizard => "Wizard", + .thief => "Thief", + .bard => "Bard", + .warrior => "Warrior", + }; + + std.debug.print("{s} (G:{} H:{} XP:{})", .{ + class_name, + c.gold, + c.health, + c.experience, + }); +} |