Skip to content

Trying to move a &mut out of a static gives confusing error #142772

@theemathas

Description

@theemathas
Contributor

Code

static DANGLING: &mut () = unsafe { &mut *(1 as *mut ()) };
const WUT: &mut () = DANGLING;

Current output

error[E0596]: cannot borrow `*DANGLING` as mutable, as `DANGLING` is an immutable static item
 --> src/lib.rs:2:22
  |
2 | const WUT: &mut () = DANGLING;
  |                      ^^^^^^^^ cannot borrow as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground` (lib) due to 1 previous error

Desired output

Mention the fact that &mut T doesn't implement Copy.

Rationale and extra context

Found while investigating #140123

Other cases

Rust Version

Reproducible on the playground with version 1.89.0-nightly (2025-06-11 e703dff8fe220b78195c)

Anything else?

No response

Activity

added
A-diagnosticsArea: Messages for errors, warnings, and lints
T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
on Jun 20, 2025
changed the title [-]Assigning a `&mut` from a `static` to a `const` gives confusing error[/-] [+]Trying to move a `&mut` out of a `static` gives confusing error[/+] on Jun 20, 2025
theemathas

theemathas commented on Jun 20, 2025

@theemathas
ContributorAuthor

A similar error occurs when moving out of a static into a variable with a type annotation:

static DANGLING: &mut () = unsafe { &mut *(1 as *mut ()) };

fn main() {
    let _x: &mut () = DANGLING;
}
error[E0596]: cannot borrow `*DANGLING` as mutable, as `DANGLING` is an immutable static item
 --> src/main.rs:4:23
  |
4 |     let _x: &mut () = DANGLING;
  |                       ^^^^^^^^ cannot borrow as mutable

For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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

        Participants

        @theemathas

        Issue actions

          Trying to move a `&mut` out of a `static` gives confusing error · Issue #142772 · rust-lang/rust