std-type

Rust Ref guard

Ref is a read guard carrying a runtime borrow, not merely a copied reference. Moving it transfers the guard; dropping it releases its contribution to the active read borrow. A clone through Ref::clone creates another guard. Expected output (not executed): 21 true true Why: The second read guard still prevents exclusive access. Common mistake: Using a.clone() when intending to clone the guard rather than its dereferenced contents.

Formal Syntax & Structure

rust syntaxrust
Ref<'a, T>

Working Example

Example Snippetrust
use std::cell::{Ref, RefCell};fn main() {    let data = RefCell::new(21);    let a = data.borrow(); let b = Ref::clone(&a);    drop(a);    println!("{} {}", *b, data.try_borrow_mut().is_err());    drop(b);    println!("{}", data.try_borrow_mut().is_ok());}
Rust Reference