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 not alive anymore. I therefore can borrow var` again to the println macro.
When you assigned to p_var
you created a mutable borrow that was in scope and alive when you tried to borrow to the println macro, which is not allowed.
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.