std::rc
最後更新
單執行緒的參考計數(reference counting)智慧指標
Rc<T> 與弱參考 Weak<T>。這個模組做什麼
Rust 規定每個值只有一個擁有者。但有些資料天生就被多方共用:圖的節點被多條邊指到、設定被多個元件讀取。
Rc<T> 讓多個擁有者共享同一份堆積上的資料。運作方式像圖書館的借閱紀錄:每
clone 一次 Rc,計數加一;每丟掉一個 Rc,計數減一;計數歸零時,資料才真正釋放。clone 只複製指標並調整計數,不複製資料本身。| 型別 | 擁有者數量 | 可否跨執行緒 | 內部能否修改 |
|---|---|---|---|
Box<T> | 1 | 視 T 而定 | 可(擁有者有 &mut) |
Rc<T> | 多個 | 不可 | 不可,需搭配 RefCell |
Arc<T> | 多個 | 可 | 不可,需搭配 Mutex 等 |
Rc 只在單一執行緒內使用;它沒有實作 Send,傳給另一個執行緒會編譯失敗。跨執行緒請改用 Arc(見 std::sync)。匯入
- use std::rc::{Rc, Weak};
Rc 與 Weak 都不在 prelude 中,需要 use。常用 API
Rc::new 與 Rc::clone
Rc::new 建立第一個擁有者。要再多一個擁有者時,慣例寫 Rc::clone(&a) 而不是 a.clone(),讓讀程式的人一眼看出這只是增加計數,不是深層複製。簽名:
- pub fn new(value: T) -> Rc<T>
- fn clone(&self) -> Rc<T>
範例:
- use std::rc::Rc;
- fn main() {
- let shared = Rc::new(vec![1, 2, 3]);
- let a = Rc::clone(&shared);
- let b = Rc::clone(&shared);
- println!("shared = {:?}", shared);
- println!("a 的總和 = {}", a.iter().sum::<i32>());
- println!("b 的長度 = {}", b.len());
- println!("指向同一份資料:{}", Rc::ptr_eq(&a, &b));
- }
輸出:
- shared = [1, 2, 3]
- a 的總和 = 6
- b 的長度 = 3
- 指向同一份資料:true
strong_count:看有幾個擁有者
Rc::strong_count 回傳目前強參考(strong reference)的數量。觀察它的變化,就能看清楚 Rc 何時釋放資料。簽名:
- pub fn strong_count(this: &Rc<T>) -> usize
範例:
- use std::rc::Rc;
- struct Noisy(&'static str);
- impl Drop for Noisy {
- fn drop(&mut self) {
- println!("釋放 {}", self.0);
- }
- }
- fn main() {
- let a = Rc::new(Noisy("資料"));
- println!("建立後:{}", Rc::strong_count(&a));
- {
- let b = Rc::clone(&a);
- println!("clone 後:{},內容 {}", Rc::strong_count(&b), b.0);
- }
- println!("b 離開作用域:{}", Rc::strong_count(&a));
- drop(a);
- println!("程式結束");
- }
輸出:
- 建立後:1
- clone 後:2,內容 資料
- b 離開作用域:1
- 釋放 資料
- 程式結束
多個擁有者共享:共用尾巴的串列
Rc 最典型的用途是讓一份資料被多個結構同時擁有。下面兩條串列共用同一段尾巴,尾巴要等兩條都不用了才釋放。簽名:
- enum List {
- Cons(i32, Rc<List>),
- Nil,
- }
範例:
- use std::rc::Rc;
- #[derive(Debug)]
- enum List {
- Cons(i32, Rc<List>),
- Nil,
- }
- use List::{Cons, Nil};
- fn total(list: &List) -> i32 {
- match list {
- Cons(v, rest) => v + total(rest),
- Nil => 0,
- }
- }
- fn main() {
- let tail = Rc::new(Cons(10, Rc::new(Cons(20, Rc::new(Nil)))));
- let x = Cons(1, Rc::clone(&tail));
- let y = Cons(2, Rc::clone(&tail));
- println!("x = {:?}", x);
- println!("y = {:?}", y);
- println!("x 總和 {},y 總和 {}", total(&x), total(&y));
- println!("tail 的擁有者:{}", Rc::strong_count(&tail));
- }
輸出:
- x = Cons(1, Cons(10, Cons(20, Nil)))
- y = Cons(2, Cons(10, Cons(20, Nil)))
- x 總和 31,y 總和 32
- tail 的擁有者:3
Rc<RefCell<T>>:共享又可修改
Rc<T> 只給共享參考(&T),所以不能直接修改內容。搭配 RefCell<T>(見 std::cell)就能在執行期檢查借用規則,讓多個擁有者都能修改同一份資料。注意:
RefCell 的 borrow_mut 若在已有其他借用時呼叫,會在執行期 panic。簽名:
- Rc<RefCell<T>>
- pub fn borrow_mut(&self) -> RefMut<'_, T>
範例:
- use std::cell::RefCell;
- use std::rc::Rc;
- struct Account {
- owner: &'static str,
- log: Rc<RefCell<Vec<String>>>,
- }
- impl Account {
- fn act(&self, what: &str) {
- self.log.borrow_mut().push(format!("{} {}", self.owner, what));
- }
- }
- fn main() {
- let log = Rc::new(RefCell::new(Vec::new()));
- let a = Account { owner: "Amy", log: Rc::clone(&log) };
- let b = Account { owner: "Ben", log: Rc::clone(&log) };
- a.act("存款 100");
- b.act("提款 30");
- a.act("查詢餘額");
- for line in log.borrow().iter() {
- println!("{}", line);
- }
- }
輸出:
- Amy 存款 100
- Ben 提款 30
- Amy 查詢餘額
Weak:不擁有的參考
如果兩個
Rc 互相指向對方,計數永遠不會歸零,記憶體就洩漏了(循環參考)。Weak<T> 是弱參考:它指向資料但不算擁有者,不影響釋放。用 Rc::downgrade 從 Rc 產生 Weak,用 upgrade 嘗試取回 Rc:資料還在回傳 Some,已釋放回傳 None。簽名:
- pub fn downgrade(this: &Rc<T>) -> Weak<T>
- pub fn upgrade(&self) -> Option<Rc<T>>
- pub fn weak_count(this: &Rc<T>) -> usize
範例:
- use std::rc::{Rc, Weak};
- fn main() {
- let weak: Weak<String>;
- {
- let strong = Rc::new(String::from("暫時的資料"));
- weak = Rc::downgrade(&strong);
- println!("strong = {}, weak = {}", Rc::strong_count(&strong), Rc::weak_count(&strong));
- println!("upgrade:{:?}", weak.upgrade());
- }
- println!("離開作用域後 upgrade:{:?}", weak.upgrade());
- }
輸出:
- strong = 1, weak = 1
- upgrade:Some("暫時的資料")
- 離開作用域後 upgrade:None
用 Weak 打破循環:父子樹
樹狀結構中,父節點擁有子節點(
Rc),子節點只需要「知道」父節點是誰(Weak)。這樣父節點被丟掉時能正常釋放,不會形成循環。簽名:
- struct Node {
- parent: RefCell<Weak<Node>>,
- children: RefCell<Vec<Rc<Node>>>,
- }
範例:
- use std::cell::RefCell;
- use std::rc::{Rc, Weak};
- struct Node {
- name: String,
- parent: RefCell<Weak<Node>>,
- children: RefCell<Vec<Rc<Node>>>,
- }
- impl Drop for Node {
- fn drop(&mut self) {
- println!("釋放 {}", self.name);
- }
- }
- fn node(name: &str) -> Rc<Node> {
- Rc::new(Node {
- name: name.to_string(),
- parent: RefCell::new(Weak::new()),
- children: RefCell::new(Vec::new()),
- })
- }
- fn main() {
- let leaf = node("leaf");
- {
- let root = node("root");
- *leaf.parent.borrow_mut() = Rc::downgrade(&root);
- root.children.borrow_mut().push(Rc::clone(&leaf));
- let parent_name = leaf.parent.borrow().upgrade().map(|p| p.name.clone());
- println!("leaf 的父節點:{:?}", parent_name);
- println!("root 有 {} 個子節點", root.children.borrow().len());
- println!("root strong = {}, weak = {}", Rc::strong_count(&root), Rc::weak_count(&root));
- }
- println!("root 已離開作用域,父節點:{:?}", leaf.parent.borrow().upgrade().map(|p| p.name.clone()));
- }
輸出:
- leaf 的父節點:Some("root")
- root 有 1 個子節點
- root strong = 1, weak = 1
- 釋放 root
- root 已離開作用域,父節點:None
- 釋放 leaf
try_unwrap 與 make_mut
Rc::try_unwrap 在只剩一個擁有者時取回內部值,否則把 Rc 原封不動以 Err 還給你。Rc::make_mut 提供寫入時複製(clone-on-write):只有自己一個擁有者就直接修改,否則先複製一份再改,不影響其他人。簽名:
- pub fn try_unwrap(this: Rc<T>) -> Result<T, Rc<T>>
- pub fn make_mut(this: &mut Rc<T>) -> &mut T
範例:
- use std::rc::Rc;
- fn main() {
- let a = Rc::new(String::from("唯一"));
- println!("{:?}", Rc::try_unwrap(a));
- let b = Rc::new(5);
- let b2 = Rc::clone(&b);
- let back = Rc::try_unwrap(b);
- println!("有兩個擁有者時:is_err = {}", back.is_err());
- drop(back);
- let mut x = Rc::new(vec![1, 2]);
- let y = Rc::clone(&x);
- Rc::make_mut(&mut x).push(3);
- println!("x = {:?}, y = {:?}, b2 = {}", x, y, b2);
- }
輸出:
- Ok("唯一")
- 有兩個擁有者時:is_err = true
- x = [1, 2, 3], y = [1, 2], b2 = 5
重點整理
Rc<T>讓多個擁有者共享資料,計數歸零才釋放- 用
Rc::clone(&a)增加擁有者,只複製指標 - 只能在單一執行緒使用,跨執行緒改用
Arc - 要修改共享資料,搭配
RefCell成為Rc<RefCell<T>> - 互相指向會循環洩漏,反向連結用
Weak,以upgrade取回