Quick and easy: Looking for reasons/explanations, why following syntax doesn’t work (aside “not being currently supported by compiler”)
const DirectionProps = packed struct(u2) {
vertical: bool,
reversed: bool,
};
const Direction = enum(DirectionProps) {
left_to_right = .{ .vertical = false, .reversed = false }, // 0b00
right_to_left = .{ .vertical = false, .reversed = true }, // 0b01
top_to_bottom = .{ .vertical = true, .reversed = false }, // 0b10
bottom_to_top = .{ .vertical = true, .reversed = true }, // 0b11
};
Since enums only accept integers as tags, why not packed structs? Since they:
- Must have define backing integer (as of more recent versions of compiler)
- Are basically a bit by bit representation of said integer
- Supports many integer operations without having to create “helper” functions
Not only that, but @intFromEnum returns backing integer.
Why not something similar, that returns backing struct?
I know I can still @bitcast it directly to said struct (and it works), but I need to specify resulting type.
I managed to get something like this working like this:
const Direction = enum(@typeInfo(DirectionProps).@"struct".backing_integer.?) {
left_to_right = @bitCast(DirectionProps{ .vertical = false, .reversed = false }),
top_to_bottom = @bitCast(DirectionProps{ .vertical = true, .reversed = false }),
right_to_left = @bitCast(DirectionProps{ .vertical = false, .reversed = true }),
bottom_to_top = @bitCast(DirectionProps{ .vertical = true, .reversed = true }),
};
and I’m getting values by:
const dir: Direction = .left_to_right;
const props: DirectionProps = @bitCast(dir);
_ = props.vertical;
_ = props.reversed;
which is a bit tedious to write, but it works.