Tired of reading long Rust documentation? Learn how smart Rust is in 1 min.
Let’s dive in:
1 let mut x = 10; // Create a mutable variable
2 let y = &mut x; // Borrow it mutably
3 println!("{}", x); // Access the variable directly
4 // println!("{}", y); // Uncommenting this will cause an error in line 3!
Here’s the cool part:
- Line 3 prints
xjust fine. - But if you uncomment line 4, Rust will throw an error at line 3.
Why? Because Rust checks if
ywill be used later, and if it will, it blocks access tox, as immutable borrow at line 3 can’t happen whileyis still valid in scope.
Pretty clever, right?
Top comments (3)
The borrow checker is doing something subtle here.
let y = &mut xborrows x mutably -- the binding x itself becomes inaccessible until y goes out of scope. This is Rust's move semantics in action.The edge case worth knowing: NLL (Non-Lexical Lifetimes) tightened the rules significantly. Before NLL, the borrow extended to the end of the block even if y was no longer used. NLL made the borrow end at the last use of y.
I ran into this on a data pipeline that held a mutable reference longer than needed. Dropped y early and the whole thing compiled. The borrow checker isn't being pedantic -- it's tracking something real.
Have you experimented with NLL in complex scenarios?
Yeah, I faced this a lot while building smart contracts on Solana.
I see that you created motedb, and I absolutely love it!
Haha, yes, it is!