从
当我确实有一个
下面是一个愚蠢的编造示例,它使用
std::cell
文档中,我了解到Cell
仅“与实现了Copy
的类型兼容”。这意味着对于非Copy
类型,我必须使用RefCell
。当我确实有一个
Copy
类型时,是否有一种单元格类型优于另一种?我假设答案是“是”,否则两种类型都不存在!那么,使用其中一种类型的好处和权衡是什么?下面是一个愚蠢的编造示例,它使用
Cell
和RefCell
来完成相同的目标:use std::cell::{Cell,RefCell};
struct ThingWithCell {
counter: Cell<u8>,
}
impl ThingWithCell {
fn new() -> ThingWithCell {
ThingWithCell { counter: Cell::new(0) }
}
fn increment(&self) {
self.counter.set(self.counter.get() + 1);
}
fn count(&self) -> u8 { self.counter.get() }
}
struct ThingWithRefCell {
counter: RefCell<u8>,
}
impl ThingWithRefCell {
fn new() -> ThingWithRefCell {
ThingWithRefCell { counter: RefCell::new(0) }
}
fn increment(&self) {
let mut counter = self.counter.borrow_mut();
*counter = *counter + 1;
}
fn count(&self) -> u8 { *self.counter.borrow_mut() }
}
fn main() {
let cell = ThingWithCell::new();
cell.increment();
println!("{}", cell.count());
let cell = ThingWithRefCell::new();
cell.increment();
println!("{}", cell.count());
}
RefCell
来获得值语义:克隆初始状态,对其进行操作,最后将修改后的状态写回单元格中。 - Matthieu M.Cell
иҺ·еҸ–еј•з”ЁиҜӯд№үпјҢеҜ№еҗ—пјҹ - ShepmasterCell
的引用。如果你想要一个值的引用,你可以使用它的UnsafeCell
组成部分,而UnsafeCell
可以给你一个指向引用值的指针...但这是不安全的(根据名称)。所以,不,Cell
不是用来操作引用的;否则就不安全了,因为它会打破借用检查。 - Matthieu M.RefCell
允许您在仅为Clone
而不是Copy
的数据上获得值语义,只要它没有被借用到其他地方。然而,它也允许您在Copy
数据上强制引用语义,这正是我的观点,因为问题假设该类型是Copy
。 - Levans