在 rust 文档:
Cell is “A mutable memory location”, and RefCell is “A mutable memory location with dynamically checked borrow rules”.
他们都提供了内部可变性,可以通过 cell 的不可变引用更改内部存储的值。
都实现了 get_mut
pub fn get_mut(&mut self) -> &mut T
Cell
定义如下:T 实现了 Send
,禁止实现 Sync
;貌似不需要是 Copy
In the old version of Rust, Cell requires the wrapped type to be Copy. Many articles still contain such outdated and misleading information. Indeed Cell has two different sets of APIs in a newer version.(存疑)
get 里面的 T 需要实现 Copy trait
// impl<T: Copy> Cell<T>
pub fn get(&self) -> T
// impl<T> Cell<T>
pub fn set(&self, val: T)
/// See the [module-level documentation](self) for more.
#[stable(feature = "rust1", since = "1.0.0")]
#[repr(transparent)]
pub struct Cell<T: ?Sized> {
value: UnsafeCell<T>,
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized> Send for Cell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Sync for Cell<T> {}
RefCell
定义:也可以跨线程传递,前提是 T 也是实现 Send。RefCell
允许可变借用与不可变借用,它在运行时追踪「借用」。
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T: ?Sized> {
borrow: Cell<BorrowFlag>,
value: UnsafeCell<T>,
}
运行时追踪会有开销,而且 RefCell
也会导致运行时 panics。
参考: