📅  最后修改于: 2023-12-03 15:04:57.702000             🧑  作者: Mango
Rust RefCell
To use RefCell
use std::cell::RefCell;
Then create a RefCellnew()
method:
let my_refcell = RefCell::new("initial value");
You can then borrow the contents of the RefCell
To borrow the contents immutably, use the .borrow()
method. This returns a reference to the contents of the RefCell
let borrowed = my_refcell.borrow();
println!("The contents of my_refcell are: {}", borrowed); // Output: The contents of my_refcell are: initial value
To borrow the contents mutably, use the .borrow_mut()
method. This returns a mutable reference to the contents of the RefCell
let mut mutable_borrowed = my_refcell.borrow_mut();
*mutable_borrowed = "new value";
println!("The contents of my_refcell are: {}", my_refcell.borrow()); // Output: The contents of my_refcell are: new value
If a mutable borrow overlaps with an immutable borrow, or if there are multiple mutable borrows, a panic will occur at runtime.
RefCell
Rust RefCell.borrow()
for immutable borrowing and .borrow_mut()
for mutable borrowing. Be aware of panics that can occur if multiple borrows overlap or if there are multiple mutable borrows. RefCell