RefCell try_borrow Detects Aliasing
try_borrow and try_borrow_mut return Err instead of panicking, showing at runtime that RefCell allows many readers or one writer but never both.
Code
use std::cell::RefCell;
fn main() {
let views = RefCell::new(0u32);
// Immutable borrows stack: two live at once
let first = views.borrow();
let second = views.borrow();
println!("two readers see {} and {}", *first, *second);
drop(second);
// Coexisting with a mutable borrow: rejected at runtime, try_borrow_mut returns Err
let conflict = views.try_borrow_mut();
println!("mut while reading rejected: {}", conflict.is_err());
drop(first);
// Once exclusivity holds, borrow_mut succeeds and the write happens in place
*views.borrow_mut() += 3;
println!("after write: {}", *views.borrow());
// Two overlapping mutable borrows are rejected too: the borrow rules move from compile time to runtime
let writer = views.borrow_mut();
let second_writer = views.try_borrow_mut();
println!("second writer rejected: {}", second_writer.is_err());
drop(writer);
println!("recovered: {}", *views.borrow());
}How the snippet works
Count the function main as the entire surface area of RefCell try_borrow Detects Aliasing.
Applying it
Running the file prints labeled results such as two readers see, mut while reading rejected:, after write: — each operation’s effect is visible in the output.
Statements that matter
let second_writer = views.try_borrow_mut();
let conflict = views.try_borrow_mut();
let writer = views.borrow_mut();
Interactive Tools for This Topic
FAQ
- What does RefCell try_borrow Detects Aliasing print when run?
- The script runs standalone; its 5 labeled outputs include `two readers see`, `mut while reading rejected:`, `after write:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.