ziglings/exercises/092_interfaces.zig

69 lines
1.6 KiB
Zig
Raw Normal View History

2023-02-11 05:12:47 -05:00
//
2023-02-11 05:43:09 -05:00
// Remeber excerices 55-57 with tagged unions.
2023-02-11 05:12:47 -05:00
//
2023-02-11 05:43:09 -05:00
// (story/explanation from Dave)
2023-02-11 05:12:47 -05:00
//
const std = @import("std");
const Ant = struct {
still_alive: bool,
pub fn print(self: Ant) void {
std.debug.print("Ant is {s}.\n", .{if (self.still_alive) "alive" else "death"});
}
};
const Bee = struct {
flowers_visited: u16,
pub fn print(self: Bee) void {
std.debug.print("Bee visited {} flowers.\n", .{self.flowers_visited});
}
};
const Grasshopper = struct {
distance_hopped: u16,
pub fn print(self: Grasshopper) void {
std.debug.print("Grasshopper hopped {} m.\n", .{self.distance_hopped});
}
};
const Insect = union(enum) {
ant: Ant,
bee: Bee,
grasshopper: Grasshopper,
pub fn print(self: Insect) void {
switch (self) {
inline else => |case| return case.print(),
}
}
};
pub fn main() !void {
var my_insects = [_]Insect{ Insect{
.ant = Ant{ .still_alive = true },
}, Insect{
.bee = Bee{ .flowers_visited = 17 },
}, Insect{
.grasshopper = Grasshopper{ .distance_hopped = 32 },
} };
2023-02-11 05:43:09 -05:00
// The daily situation report, what's going on in the garden
2023-02-11 05:12:47 -05:00
try dailyReport(&my_insects);
}
2023-02-11 05:43:09 -05:00
// Through the interface we can keep a list of various objects
// (in this case the insects of our garden) and even pass them
// to a function without having to know the specific properties
// of each or the object itself. This is really cool!
2023-02-11 05:12:47 -05:00
fn dailyReport(insectReport: []Insect) !void {
std.debug.print("Daily insect report:\n", .{});
for (insectReport) |insect| {
insect.print();
}
}
2023-02-11 05:43:09 -05:00
// Interfaces... (explanation from Dave)