Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in Zig (like usize to i32 and more)

Tags:

casting

zig

As in other higher then asm level languages like Java, i want to cast values, compare it and more.

For example filling array like this:

    var array: [10]i32 = undefined;

    for (0..array.len) |i|
        array[i] = i;

But compiler says:

C:\Zig\projects\test\src>zig run main.zig
main.zig:7:20: error: expected type 'i32', found 'usize'
        array[i] = i;
                   ^
main.zig:7:20: note: signed 32-bit int cannot represent all possible unsigned 64-bit values
referenced by:
    callMain: C:\Zig\lib\std\start.zig:585:32
    initEventLoopAndCallMain: C:\Zig\lib\std\start.zig:519:34
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

and i have no idea how to fix this, because all ways to do this before doesnt work. And also i need u32 to i32, f32 to i32 and so for later. Please help me

like image 678
varikoz272 Avatar asked Dec 28 '25 21:12

varikoz272


1 Answers

You need to use @intCast to explicitly cast the number to a smaller type.

var array: [10]i32 = undefined;

for (0..array.len) |i|
    array[i] = @intCast(i);

Keep in mind that if you use @intCast and the number doesn't fit into the smaller type, it will trigger undefined behaviour.

like image 88
dante Avatar answered Jan 03 '26 16:01

dante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!