Why is the mutable reference copied?

⚓ rust    📅 2025-06-13    👤 surdeus    👁️ 2      

surdeus

Hi,

I learned that shared references can be copied, but mutable references cannot, and gave it a try. But the result is confusing.

Rust rejected t1 as expected, but it accepts t2. Why?

fn main() {
    t1();
    t2();
}

fn t1() {
    let mut a: i32 = 0;
    let r1 = &mut a;

    let r2 = r1;            // error[E0382]: borrow of moved value: `r1`

    println!("{}", r1);
}

fn t2() {
    let mut a: i32 = 0;
    let r1 = &mut a;

    let r2: &mut i32 = r1;  // OK!

    println!("{}", r1);
}

2 posts - 2 participants

Read full topic

🏷️ rust_feed