Cell

Cell智能指针用于提供内部可变性(内部使用了unsafe)。

use std::cell::Cell;
 
fn main() {
    let c = Cell::new("asdf");
    let one = &c;
    let two = &c;
    one.set("qwer");
    two.set("tyui");
    println!("{:?},{:?}", one, two);
}

由于最多只能拥有一个可变引用,使用 &mut 无法实现上述逻辑。

Cell的包裹的对象必须实现Copy特征。如将上述代码中的&str改为String类型,即报错。