Skip to content

The diagnostic for &[u8] to [char] seems to be wrong in some way #118790

Closed
@wyattscarpenter

Description

@wyattscarpenter

Code

fn main() {
  "example".as_bytes() as [char];
}

Current output

error[E0620]: cast to unsized type: `&[u8]` as `[char]`
 --> src\main.rs:2:5
  |
2 |     "example".as_bytes() as [char];
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
help: consider using an implicit coercion to `&[char]` instead
 --> src\main.rs:2:5
  |
2 |     "example".as_bytes() as [char];
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0620`.

Desired output

error[E0605]: non-primitive cast: `&[u8]` as `&[char]`
 --> src\main.rs:2:5
  |
2 |     "example".as_bytes() as &[char];
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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`.

Rationale and extra context

The current help message is very curious because it says "help: consider using an implicit coercion to &[char] instead", but then prints exactly the same code as before. Maybe it should actually be suggesting removing the as [char] part? Anyway, when you put in the & in front of the [char], you get the Desired Output, above, which I think is the more correct error?

Other cases

let arr: &[u8] = &[0, 2, 3]; //It's not just because of the str type involved either; this case also gives the same error message
arr as [char];

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions