rust-lang / rust-lang/rust

Type annotation on `let _` binding materializes the value

Open
#160,217 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

needs-triage
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

This program is fine:

fn main() {
    let mut x = &1;
    unsafe { (&raw mut x).cast::<usize>().write(0) };
    let _ = x; // fine
}

x contains invalid data, but we're just mentioning the place without loading from it.

However, this program has UB according to Miri:

fn main() {
    let mut x = &1;
    unsafe { (&raw mut x).cast::<usize>().write(0) };
    let _: &_ = x; // errors
}

Somehow, with a type annotation, the mentioned place becomes an actually loaded-from place.

For this case that seems like an odd inconsistency, but things become more tricky if we consider that there can be coercions involved, including coercions from uninhabited types to any types. Those must actually materialize the input value, obviously. (I seems to remember we have an issue for such coercions somewhere?)

Cc @Nadrieril

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running both Rust examples under Miri and compare the behavior of the unannotated and annotated let _ bindings. Investigate how type annotations and coercions determine whether the place is materialized, including coercions from uninhabited types. Done means the language behavior is clarified and the inconsistency is resolved or documented with coverage for these cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.