Is this error happening because of variance or not?. Explain mental model

⚓ Rust    📅 2025-07-09    👤 surdeus    👁️ 2      

surdeus

#![allow(warnings)]
fn main() {
   
   
    let mut z = 4;

    // x: &{8,11} mut u32 = &{8,11} mut 4
    let mut x: &mut u32 = &mut z;

   // f: &{11} mut &{8,11} mut u32 =&{11} mut &{8,11} mut 4
    let mut f: &mut &mut u32 = &mut x;

   
    let mut q = 44;

    // s: &{17,25} mut u32 = &{17,25} mut 4
    let mut s: &mut u32 = &mut q;

    // x: &{20} mut u32 = &{20} mut 44
    x = &mut s;
    
   // f: &{23,25} mut &{17,25} mut u32 =&{23,25} mut &{17,25} mut 4
    f = &mut s;
   
   println!("{}",f);


}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `s` as mutable more than once at a time
  --> src/main.rs:23:9
   |
20 |     x = &mut s;
   |         ------ first mutable borrow occurs here
...
23 |     f = &mut s;
   |         ^^^^^^
   |         |
   |         second mutable borrow occurs here
   |         first borrow later used here

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

2 posts - 2 participants

Read full topic

🏷️ rust_feed