Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot borrow `var` as immutable because it is also borrowed as mutable

While trying to compile the following code, im getting an error:

error[E0502]: cannot borrow var as immutable because it is also borrowed as mutable

fn increment(num : &mut i32){
    *num = *num +1;
}

fn main() {
    let mut var : i32 = 123;
    let p_var: &mut i32   = &mut var;

    println!("{}", var);
    increment(p_var);
}

I have no clue what does it mean, can someone explain me exacly why am I getting this error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

fn increment(num: &mut i32){
    *num = *num +1;
}

fn main() {
    let mut var : i32 = 123;
    
    println!("{}", var);
    increment(&mut var);
    println!("{}", var);
}

worked for me.

I, myself, am a Rust beginner, too. So, here is what my view on this is ( I MAY be utterly wrong ):

In this code var never gives up ownership and has no mutable borrows that are still in scope when it borrows immutably. I therefore can borrow it mutably to the increment function. After it has returned that borrow is out of scope. I therefore can borrow it again to the println macro.

When you assigned to p_var that wasn’t the case any more.

This is what the incredible cargo told me:

error[E0502]: cannot borrow `var` as immutable because it is also borrowed as mutable
  --> src/main.rs:9:20
   |
7  |     let p_var : &mut i32 = &mut var;
   |                            -------- mutable borrow occurs here
8  |
9  |     println!("{}", var);
   |                    ^^^ immutable borrow occurs here
10 |     increment(p_var);
   |               ----- mutable borrow later used here
   |

It would be great if some more experienced rustacian could verify (or correct) my reasoning and assessment.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading