How to create a neat cast?

My code is:

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

var a: i8 = 127;
var b: i8 = 1;

test "test1" {
    try expect(@as(i64, a + b) == 128);
}

test "test2" {
    try expect(@as(i64, a) + @as(i64, b) == 128);
}
  • Description: if i sum a and b then cast in “test1”, it will have a overflow panic. So i have to cast one by one to sum in “test2”.
  • Question: This method is quite lengthy, is there a way to make it simpler? Thanks

You probably already know this, but the only way I know of to simplify it is to use a larger type, for example, i16, instead of i8 for a and b, since the sum of 128 and 1 cannot be represented in an i8. Zig is very strict about type conversions and requires them to be explicit.

Edit: even using u8 would be sufficient.

1 Like

Yeah l thought about that, but i still hope another way that don’t need to change type of unnecessary variables.

It looks like if you cast the first value, the second one is coerced safely to the same type:

    try expect(@as(i16, a) + b == 128);

This worked for me with version 0.10.0-dev.4217+9d8cdb855.

1 Like

that’s it!!! also with zig 0.9.1