Ziglang 0.10.0 interfaces

mail@pastecode.io avatar
unknown
plain_text
2 years ago
662 B
11
Indexable
Never
const std = @import("std");

const Cat = struct {
    anger_level: usize,

    pub fn talk(self: Cat) void {
        std.debug.print("Cat: meow! (anger lvl {})", .{self.anger_level});
    }
};

const Dog = struct {
    name: []const u8,

    pub fn talk(self: Dog) void {
        std.debug.print("{s} the dog: bark!", .{self.name});
    }
};

const Animal = union(enum) {
    cat: Cat,
    dog: Dog,

    pub fn talk(self: Animal) void {
        switch (self) {
            inline else => |case| case.talk(),
        }
    }
};

pub fn main() !void {
    var animal = Animal{ .dog = .{ .name = "Spotty" } };
    animal.talk();
}