【发布时间】:2015-05-16 13:01:53
【问题描述】:
从std::cell documentation,我看到Cell“仅与实现Copy 的类型兼容”。这意味着我必须将RefCell 用于非Copy 类型。
当我确实拥有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());
}
【问题讨论】:
标签: rust