const std = @import("std");
const Animal = union(enum) {
cat: Cat,
dog: Dog,
pub fn talk(self: Animal) void {
switch (self) {
inline else => |case| case.talk(),
}
}
};
const Cat = struct {
anger_level: usize,
pub fn talk(self: Cat) void {
std.debug.print("[Cat] Meow! (anger Lv {})\n", .{self.anger_level});
}
};
const Dog = struct {
name: []const u8,
pub fn talk(self: Dog) void {
std.debug.print("[Dog] I'm a {s}\n", .{self.name});
}
};
pub fn main() !void {
const cat = Animal{ .cat = .{ .anger_level = 100 } };
cat.talk();
const dog = Animal{ .dog = .{ .name = "lilly" } };
dog.talk();
const animals = [_]Animal{
cat,
dog,
};
for (animals) |a| {
a.talk();
}
}
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme