Unexplainable Borrow Lock
⚓ Rust 📅 2026-01-01 👤 surdeus 👁️ 1I was originally investigating how the compiler performs borrow checking, but I found a strange and counterintuitive behavior associated with nested borrows, so let me share it here. In the following code, apparently, there is no reason to forbid move ptr_global at the very end. Neverthless, it does not get compiled. You can see the compilation log below.
fn _lifetime_bound_test<'a, 'b>(_lhs: &'a mut &'a String, _rhs: &'b String) {
println!("There is no interaction between the inputs.");
}
fn main() {
let a = String::from("a");
let ptr_global = &mut &a; // More formally, ptr_global: &mut 'global &'global String.
{
let b = String::from("b");
let _ptr_inner = &b; // More formally, ptr_inner: &'inner String.
_lifetime_bound_test(ptr_global, _ptr_inner);
}
let _can_be_moved = ptr_global;
}
------------------------------------------------COMPILATION LOG----------------------------------------------------
error[E0505]: cannot move out of ptr_global because it is borrowed
--> src\main.rs:15:25
|
7 | let ptr_global = &mut &a; // More formally, ptr_global: &mut 'global &'global String.
| ---------- binding ptr_global declared here
...
12 | _lifetime_bound_test(ptr_global, _ptr_inner);
| ---------- borrow of *ptr_global occurs here
...
15 | let _can_be_moved = ptr_global;
| ^^^^^^^^^^
| |
| move out of ptr_global occurs here
| borrow later used here
For more information about this error, try rustc --explain E0505.
error: could not compile borrow_lock (bin "borrow_lock") due to 1 previous error.
If I remove the _lifetime_bound_test part, it gets compiled without any problems.
I would really appritiate if anyone could explain what is happening.
3 posts - 3 participants
🏷️ Rust_feed