Zig: Slice length does not cast correctly

Created on 19 Nov 2019  路  5Comments  路  Source: ziglang/zig

test "slice len bug" {
    var list = [_]i32{ 1, 2, 3, 4 };
    const slice = list[0..];
    var baz: usize = 42;
    var bar: u32 = @as(u32, baz);
    var foo: u32 = @as(u32, slice.len);
}

generates test.zig:5:20: error: expected type 'u32', found 'usize' instead of compiling

Edit: Looks like this probably shouldn't compile. Just not a terribly helpful error.

enhancement

Most helpful comment

Here's what it looks like to add a hint for failed type coercion: 8ecd6c4d8c021f7778b4959bdf75204dfd2d1946

@dimenus's test case now gives:

/home/andy/dev/zig/build/test.zig:5:20: error: expected type 'u32', found 'usize'
    var bar: u32 = @as(u32, baz);
                   ^
/home/andy/dev/zig/build/test.zig:5:20: note: unsigned 32-bit int cannot represent all possible unsigned 64-bit values
    var bar: u32 = @as(u32, baz);
                   ^

All 5 comments

This is expected behaviour: a usize can not (on your target at least) fit into a u32. See @intCast or @truncate.

Edit: Looks like this probably shouldn't compile. Just not a terribly helpful error.

What would a helpful error look like?

Edit: Looks like this probably shouldn't compile. Just not a terribly helpful error.

What would a helpful error look like?

Something about as not being able to coerce a type into a type of a smaller size.

Something about as not being able to coerce a type into a type of a smaller size.

test.zig:5:20: error: expected type 'u32', found 'usize'. Cannot safety type coerce usize to u32.
Did you mean: var bar: u32 = @intCast(u32, baz); ?

We should probably start a proposal for compiler error improvements. It's an enormous task.

Here's what it looks like to add a hint for failed type coercion: 8ecd6c4d8c021f7778b4959bdf75204dfd2d1946

@dimenus's test case now gives:

/home/andy/dev/zig/build/test.zig:5:20: error: expected type 'u32', found 'usize'
    var bar: u32 = @as(u32, baz);
                   ^
/home/andy/dev/zig/build/test.zig:5:20: note: unsigned 32-bit int cannot represent all possible unsigned 64-bit values
    var bar: u32 = @as(u32, baz);
                   ^
Was this page helpful?
0 / 5 - 0 ratings

Related issues

komuw picture komuw  路  3Comments

andrewrk picture andrewrk  路  3Comments

fengb picture fengb  路  3Comments

dobkeratops picture dobkeratops  路  3Comments

S0urc3C0de picture S0urc3C0de  路  3Comments