Skip to content

Surprising type inference failure around "as" #106672

Open
@RalfJung

Description

@RalfJung

The following code works fine:

fn test(x: usize) {
    let v: [u32; 4] = [[0, 1, 2, 3], [4, 5, 6, 7]][x];
}

Hence I would expect that this also builds:

fn test(x: usize) {
    let v = [[0, 1, 2, 3], [4, 5, 6, 7]][x] as [u32; 4];
}

However, it does not:

error[[E0605]](https://doc.rust-lang.org/stable/error-index.html#E0605): non-primitive cast: `[i32; 4]` as `[u32; 4]`
 --> src/lib.rs:2:13
  |
2 |     let v = [[0, 1, 2, 3], [4, 5, 6, 7]][x] as [u32; 4];
  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object

For more information about this error, try `rustc --explain E0605`.
error: could not compile `playground` due to previous error

Looks like it inferred the integers to be i32. Proper use of the type information provided by as should enable it to infer u32 instead. This already happens successfully in simpler cases such as [0, 1, 2, 3] as [u32; 4].

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-inferenceArea: Type inferenceC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions