Using expectEqual

Is this the best way to use expectEqual?

fn add(a: i64, b: i64) i64 {
    return a + b;
}

test "basic test" {
    try std.testing.expectEqual(@as(i64, 10), add(3, 7));
}

Without the @as the test doesn't even compile:

./src/main.zig:12:40: error: expected type 'comptime_int', found 'i64'
    try std.testing.expectEqual(10, add(3, 7));

Having to use @as seems makes the test less readable. It seems to me inferring the type of expected from the type of actual would make more sense.

6 points · 4 comments · view on lemmy.world

4 Comments

huntrss@lemmy.world · 2 pts · 3y
[ removed ]
LinuxUserGD@feddit.de · 1 pts · 3y (2 replies)

Should work if "10" is also declared as a variable with type "i64" I think?

aion@lemmy.world · 1 pts · 3y (1 reply)

Sure, you could do:

    const ten: i64 = 10;
    try std.testing.expectEqual(ten, add(3, 7));

Is there a way to write an i64 literal?

xzqtlmn@lemmy.world · 2 pts · 3y

If we look at the signature expectEqual(expected: anytype, actual: @TypeOf(expected)) !void, notice that the second arg's type depends on the first arg's type.

To avoid using @as coercion, we can just swap the passing arguments. comptime_int can be inferred as i64, not the other way around. And that makes sense because literal values are unsized.

suff@piefed.social · 1 pts · 304d

Did you try casting like this? Doesn't read any better though.

std.testing.expectEqual(10, @as(comptime_int, add(3, 7))