@enumFromInt changed

@enumFromInt, which is deprecated is more flexible than @fromBackingInt.
The latter one only excepts an int of the correct size.
Understandable but also a bit inconvenient. Is the inflexibility intended?
Did we lose the flexibility of the deprecated version?

If you have an int of the wrong size, you can use casting or truncating builtins like @intCast(), since @fromBackingInt() knows the size of integer to expect.

3 Likes

The change was intentional. @enumFromInt silently performed an @intCast on its arg anyway, now it’s explicit. Since @fromBackingInt provides a result type to its arg you no longer have to manually provide one with e.g. @as if you want to @truncate instead of the implicit int cast or if you have something like this:

const Enum = enum(u8) {
    a,
    b,
    c,
};

fn foo(x: u32) Enum {
    // The switch prongs would peer resolve to `comptime_int` if there was no `u8` result type,
    // resulting in a compile error as `comptime_int` is a comptime-only type ...
    return @fromBackingInt(switch (x) {
        123 => 0,
        456 => 1,
        789 => 2,
        else => unreachable,
    });
}

fn bar(x: u32) Enum {
    // ... which is exactly what happens with `@enumFromInt`. We get a compile error!
    return @enumFromInt(switch (x) {
        123 => 0,
        456 => 1,
        789 => 2,
        else => unreachable,
    });
}