Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding an explicit type annotation causes unexpected implicit reborrow #121485

Closed
theemathas opened this issue Feb 23, 2024 · 1 comment
Closed

Comments

@theemathas
Copy link
Contributor

This code compiles and prints 10:

fn main() {
    let mut a: i32 = 10i32;
    let b: &mut i32 = &mut a;
    {
        let _c: &mut i32 = b;
    }
    println!("{b}");
}

playground

This code doesn't compile (the only difference is the lack of the type annotation on _c):

fn main() {
    let mut a: i32 = 10i32;
    let b: &mut i32 = &mut a;
    {
        let _c = b;
    }
    println!("{b}");
}

playground

The compile error is:

error[E0382]: borrow of moved value: `b`
 --> src/main.rs:7:15
  |
3 |     let b: &mut i32 = &mut a;
  |         - move occurs because `b` has type `&mut i32`, which does not implement the `Copy` trait
4 |     {
5 |         let _c = b;
  |                  - value moved here
6 |     }
7 |     println!("{b}");
  |               ^^^ value borrowed here after move
  |
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

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

I expected either both versions of the code to compile, or neither to compile. Instead, it appears that adding a type annotation for _c causes rust to do an implicit reborrow. I thought that implicit reborrow can't happen on simple assignments like this. And why would a type annotation cause a reborrow anyway?

Meta

This issue occurs on the playground, both at stable (1.76.0), and at nightly (2024-02-22 397937d).

@theemathas theemathas added the C-bug Category: This is a bug. label Feb 23, 2024
@rustbot rustbot added the needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. label Feb 23, 2024
@theemathas
Copy link
Contributor Author

theemathas commented Feb 23, 2024

Duplicate of rust-lang/reference#788. Oops.

@theemathas theemathas closed this as not planned Won't fix, can't repro, duplicate, stale Feb 23, 2024
@saethlin saethlin removed C-bug Category: This is a bug. needs-triage This issue may need triage. Remove it if it has been sufficiently triaged. labels Feb 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants