std-method

Rust RefCell::try_borrow and try_borrow_mut

Use fallible borrowing when a conflict is an expected possibility. The methods return Result with an appropriate borrow error instead of panicking because of an incompatible existing borrow. They do not wait for another guard to finish. Expected output (not executed): true 7 Why: After the read guard is dropped, mutation succeeds. Common mistake: Unwrapping the Result unconditionally when conflict is expected.

Formal Syntax & Structure

rust syntaxrust
cell.try_borrow(); cell.try_borrow_mut()

Working Example

Example Snippetrust
use std::cell::RefCell;fn main() {    let n = RefCell::new(4);    let read = n.borrow();    println!("{}", n.try_borrow_mut().is_err());    drop(read);    if let Ok(mut write) = n.try_borrow_mut() { *write += 3; }    println!("{}", *n.borrow());}
Rust Reference