📜  Rust RefCell(T)(1)

📅  最后修改于: 2023-12-03 15:04:57.702000             🧑  作者: Mango

Rust RefCell

Rust RefCell is a type in Rust's standard library that provides interior mutability. This means that the contents of the RefCell can be mutated even though the entire RefCell is considered immutable.

How to Use RefCell

To use RefCell, first import it from the standard library:

use std::cell::RefCell;

Then create a RefCell instance. The initial value inside the RefCell is specified with the new() method:

let my_refcell = RefCell::new("initial value");

You can then borrow the contents of the RefCell. There are two types of borrowing: immutable and mutable.

Immutable Borrowing

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
Mutable Borrowing

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
Panics

If a mutable borrow overlaps with an immutable borrow, or if there are multiple mutable borrows, a panic will occur at runtime.

When to Use RefCell

RefCell should be used when you need to mutate data inside an object that is otherwise treated as immutable. A common use case is when implementing interior mutability for a struct that is shared between multiple threads.

Conclusion

Rust RefCell provides interior mutability, allowing the contents of an immutable object to be mutated. Use .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 is useful for implementing interior mutability for shared objects between threads.