Hey guys, I'm trying to figure out tagged enums, here are my types
const std = @import("std");
const CollisionDetectorType = enum {
rectangle,
circle,
triangle,
};
pub const Rectangle = struct {
width: f16,
height: f16,
fn getArea(self: *Rectangle) f32 {
return self.width * self.height;
}
};
const Circle = struct {
radius: f16,
fn getArea(self: *Circle) f32 {
return std.math.pi * self.radius * self.radius;
}
};
const Triangle = struct {
height: u16,
base: u16,
fn getArea(self: *Triangle) f32 {
return self.height * self.base / 2;
}
};
pub const CollisionDetector = union(CollisionDetectorType) {
rectangle: Rectangle,
circle: Circle,
triangle: Triangle,
};
and here is how I create these structs and use them
const rectDetector = CollisionDetectorTypes.CollisionDetector{ .rectangle = .{ .width = 20, .height = 20 } };
const circleDetector = CollisionDetectorTypes.CollisionDetector{ .circle = .{ .radius = 15 } };
switch (rectDetector) {
.rectangle => |rect| {
raylib.drawRectangle(300, 400, rect.width, rect.height, raylib.Color.blue);
},
else => unreachable,
}
switch (circleDetector) {
.circle => |circle| {
raylib.drawCircle(400, 400, circle.radius, raylib.Color.red);
},
else => unreachable,
}
I'm pretty sure I'm doing something wrong, because there is no way that I have to switch all of my collision structs to know if they are rectangle or circle even though I just passed either rectangle or circle to them. What is the correct way of doing this pattern match so it isn't so extensive?