05-Cell and RefCell

Cell and RefCell — Rust By Practice

内容来源 · Rust By Practice / Rust 语言实战

原文链接: https://practice-rust.beatai.org/smart-pointers/cell-refcell.html

Cell and RefCell

Cell<T> 和 RefCell<T> 提供内部可变性:在不可变引用存在时也能修改数据。RefCell 在运行时检查借用规则。

  1. 🌟
1
2
3
4
5
6
7
8
9
// 让代码工作
use std::cell::Cell;

fn main() {
    let c = Cell::new(5);
    c.set(10);
    assert_eq!(c.get(), 10);
    println!("Success!");
}
  1. 🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// 让代码工作
use std::cell::RefCell;

fn main() {
    let data = RefCell::new(5);
    {
        let mut r = data.borrow_mut();
        *r += 1;
    }
    assert_eq!(*data.borrow(), 6);
    println!("Success!");
}
  1. 🌟🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 让代码工作
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Debug)]
enum List {
    Cons(i32, RefCell<Rc<List>>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
    let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));

    if let Some(link) = Rc::into_inner(a) {
        if let Cons(_, ref next) = link {
            *next.borrow_mut() = Rc::clone(&b);
        }
    }

    println!("Success!");
}
  1. 🌟🌟
1
2
3
4
5
6
7
8
9
// 填空
use std::cell::RefCell;

fn main() {
    let s = RefCell::new(String::from("hello"));
    s.borrow_mut().push_str(", world");
    assert_eq!(s.borrow().as_str(), __);
    println!("Success!");
}

你可以在这里找到答案(在 solutions 路径下),但请只在需要时使用

最后修改 August 23, 2026: 更新 (499855b16)