Skip to content

Bad suggestion when *raw_ptr is used where a reference is expected #135580

Closed
@RalfJung

Description

@RalfJung

Code

fn foo(bar: *const [u8]) {
   let baz: &[u8] = unsafe { *bar };
}

Current output

error[E0308]: mismatched types
 --> src/lib.rs:2:30
  |
2 |    let baz: &[u8] = unsafe { *bar };
  |                              ^^^^ expected `&[u8]`, found `[u8]`
  |
help: consider removing deref here
  |
2 -    let baz: &[u8] = unsafe { *bar };
2 +    let baz: &[u8] = unsafe { bar };
  |

Desired output

error[E0308]: mismatched types
 --> src/lib.rs:2:30
  |
2 |    let baz: &[u8] = unsafe { *bar };
  |                              ^^^^ expected `&[u8]`, found `[u8]`
  |
help: consider creating a reference here
  |
2 -    let baz: &[u8] = unsafe { *bar };
2 +    let baz: &[u8] = unsafe { &*bar };
  |

Rationale and extra context

The current suggestion is plain wrong, the result does not build.

Note that one definitely wants the & to go inside the unsafe block to avoid creating a temporary! For this example, the type is non-Copy so a temporary wouldn't even be possible, but in other cases both ways could compiler but they do not behave the same.

Other cases

Rust Version

current nightly

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-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