rust-lang / rust-lang/rust

A `&mut` in a const in a referenced literal doesn't get const-promoted

Open
#146,108 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-constant-promotion A-ZST C-bug T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

const A: &'static mut () = unsafe { std::mem::transmute(1usize) };

fn main() {
    let _x: &'static (&'static mut (),) = &(A,);
}

I think that the above code should compile, due to const promotion. Instead, I got the following error:

error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:4:44
  |
4 |     let _x: &'static (&'static mut (),) = &(A,);
  |             ---------------------------    ^^^^ creates a temporary value which is freed while still in use
  |             |
  |             type annotation requires that borrow lasts for `'static`
5 | }
  | - temporary value is freed at the end of this statement

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

Using a struct literal or an array literal instead of a tuple literal also result in a similar error.

The following modifications to the code causes the code to compile:

Using `&` instead of `&mut` makes the code compile
const A: &'static () = unsafe { std::mem::transmute(1usize) };

fn main() {
    let _x: &'static (&'static (),) = &(A,);
}
Putting the `&mut` inside something else in the const makes the code compile
const A: Option<&'static mut ()> = Some(unsafe { std::mem::transmute(1usize) });

fn main() {
    let _x: &'static (Option<&'static mut ()>,) = &(A,);
}
Omitting the tuple literal makes the code compile
const A: &'static mut () = unsafe { std::mem::transmute(1usize) };

fn main() {
    let _x: &'static &'static mut () = &A;
}

This seems rather inconsistent.

Meta

Reproducible on the playground with version 1.91.0-nightly (2025-08-31 07d246fc6dc227903da2)

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 the provided Rust reproduction on the reported nightly version and compare the tuple, struct, array, reference, and Option variants. Trace the compiler's const-promotion handling for a directly referenced &mut value; done means the original program compiles consistently with the stated const-promotion expectation and has coverage for the regression.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.