#Error with @as: expected type 'f32', found 'usize' in a for loop

1 messages · Page 1 of 1 (latest)

prisma vortex
#

Hi,
I'm getting this error when trying to convert the index from a for loop into a float.


const row = [_]u8{'x', 'y', 'z', 'p'};

pub fn main() !void {

    for (row) |tile, index| {
        // this works
        // const x: usize = 5;
        // _ = index;

        // this doesn't work
        const x = @as(f32, index);

        std.debug.print("tile: {c}, x: {d:0.2}\n", .{tile, x});
    }
}

The error I get is:

        const x = @as(f32, index);
                           ^~~~~

What I find weird is that it works using another usize like in the commented part, but with the index it doesn't.

I'm using the latest zig master. Am I doing something wrong or is this a bug in zig?

rigid bobcat
#

use @intToFloat

#

@as will only work with things that can be converted implicitly

prisma vortex
#

Oh, that works. Thanks!
But why is one usize able to be converted implicitly and not the other? what's the difference?
Is there a table for which types can be converted implicitly to others?

rigid bobcat
#

integers can implicitly widen, but not shrink

#

Pretty sure its documented under @as

prisma vortex
#

The docs say This cast is allowed when the conversion is unambiguous and safe
I don't understand why const x: usize = 5; would be safer than the index? Does the compiler keep track that it originally comes from a comptime_int?

rigid bobcat
#

yeah, the type isn't actually usize until comptime is over