#any way to avoid cast?

1 messages · Page 1 of 1 (latest)

lean cove
#

IIUC, the reason a cast is needed in the code below is that i8 and comptime_int are different types and literal integers have the type comptime_int. Is there any way to avoid needing the @as cast? It feels tedious and likely trips up a lot of beginners.

const std = @import("std");
const expectEqual = std.testing.expectEqual;

test "casting" {
    var a: i8 = 0;
    // This gives "error: unable to resolve comptime value".
    try expectEqual(0, a);
    // This works.
    try expectEqual(@as(i8, 0), a);
}
brave valley
#

The reason is due to how expectEqual is defined (https://ziglang.org/documentation/master/std/#A;std:testing.expectEqual)
fn (a: anytype, b: @TypeOf(a)). The second arg must coerce to the type of the first. In the case of f(0, a), the first is comptime_int but the second is runtime i8 and cant coerce to comptime. If you put it the other way around however, f(a, 0), the comptime_int can coerce to runtime i8 and that should work