The mutable reference I return from a function in Rust seems to violate the borrowing rules — how is this possible?
I have a mutable variable and a mutable reference to it. When I pass this reference to a function and return it back from there, it seems to violate Rust’s borrowing rules. What’s the reason for this?
I can see why this code worked.
fn main(){
let mut x=5;
let a = & mut x;
let b = & mut x;
let c = & mut x;
}
I can see why this code failed.
fn main() {
let mut a = 3;
let b = &mut a;
let c = &mut a;
println!("{b}");
}
But I don’t understand why the code I see as the second one works.
fn func(reference1: &mut i32) -> &mut i32 {
reference1
}
fn main() {
let mut variable: i32 = 0;
let reference = &mut variable;
let returned_ref = func(reference);
*returned_ref += 1;
println!("reference : {}", *reference);
}
As far as I understand, in Rust the lifetime of a reference is determined at compile time — starting from the moment it is first created until the moment it is last used. In this case, in the code, the lifetime of reference begins, and then the lifetime of returned_ref begins. At that exact moment, there are two active mutable references. Then, returned_ref’s lifetime ends, and finally reference’s lifetime ends