Skip to content

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

@theemathas

Description

@theemathas
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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-ZSTArea: Zero-sized types (ZSTs).A-constant-promotionArea: constant promotionC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions