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)。

匯入


  1. use std::rc::{Rc, Weak};

Rc 與 Weak 都不在 prelude 中,需要 use。

常用 API


Rc::new 與 Rc::clone


Rc::new 建立第一個擁有者。要再多一個擁有者時,慣例寫 Rc::clone(&a) 而不是 a.clone(),讓讀程式的人一眼看出這只是增加計數,不是深層複製。
簽名:
  1. pub fn new(value: T) -> Rc<T>
  2. fn clone(&self) -> Rc<T>

範例:
  1. use std::rc::Rc;
  2. fn main() {
  3. let shared = Rc::new(vec![1, 2, 3]);
  4. let a = Rc::clone(&shared);
  5. let b = Rc::clone(&shared);
  6. println!("shared = {:?}", shared);
  7. println!("a 的總和 = {}", a.iter().sum::<i32>());
  8. println!("b 的長度 = {}", b.len());
  9. println!("指向同一份資料:{}", Rc::ptr_eq(&a, &b));
  10. }

輸出:
  1. shared = [1, 2, 3]
  2. a 的總和 = 6
  3. b 的長度 = 3
  4. 指向同一份資料:true

strong_count:看有幾個擁有者


Rc::strong_count 回傳目前強參考(strong reference)的數量。觀察它的變化,就能看清楚 Rc 何時釋放資料。
簽名:
  1. pub fn strong_count(this: &Rc<T>) -> usize

範例:
  1. use std::rc::Rc;
  2. struct Noisy(&'static str);
  3. impl Drop for Noisy {
  4. fn drop(&mut self) {
  5. println!("釋放 {}", self.0);
  6. }
  7. }
  8. fn main() {
  9. let a = Rc::new(Noisy("資料"));
  10. println!("建立後:{}", Rc::strong_count(&a));
  11. {
  12. let b = Rc::clone(&a);
  13. println!("clone 後:{},內容 {}", Rc::strong_count(&b), b.0);
  14. }
  15. println!("b 離開作用域:{}", Rc::strong_count(&a));
  16. drop(a);
  17. println!("程式結束");
  18. }

輸出:
  1. 建立後:1
  2. clone 後:2,內容 資料
  3. b 離開作用域:1
  4. 釋放 資料
  5. 程式結束

多個擁有者共享:共用尾巴的串列


Rc 最典型的用途是讓一份資料被多個結構同時擁有。下面兩條串列共用同一段尾巴,尾巴要等兩條都不用了才釋放。
簽名:
  1. enum List {
  2. Cons(i32, Rc<List>),
  3. Nil,
  4. }

範例:
  1. use std::rc::Rc;
  2. #[derive(Debug)]
  3. enum List {
  4. Cons(i32, Rc<List>),
  5. Nil,
  6. }
  7. use List::{Cons, Nil};
  8. fn total(list: &List) -> i32 {
  9. match list {
  10. Cons(v, rest) => v + total(rest),
  11. Nil => 0,
  12. }
  13. }
  14. fn main() {
  15. let tail = Rc::new(Cons(10, Rc::new(Cons(20, Rc::new(Nil)))));
  16. let x = Cons(1, Rc::clone(&tail));
  17. let y = Cons(2, Rc::clone(&tail));
  18. println!("x = {:?}", x);
  19. println!("y = {:?}", y);
  20. println!("x 總和 {},y 總和 {}", total(&x), total(&y));
  21. println!("tail 的擁有者:{}", Rc::strong_count(&tail));
  22. }

輸出:
  1. x = Cons(1, Cons(10, Cons(20, Nil)))
  2. y = Cons(2, Cons(10, Cons(20, Nil)))
  3. x 總和 31,y 總和 32
  4. tail 的擁有者:3

Rc<RefCell<T>>:共享又可修改


Rc<T> 只給共享參考(&T),所以不能直接修改內容。搭配 RefCell<T>(見 std::cell)就能在執行期檢查借用規則,讓多個擁有者都能修改同一份資料。
注意:RefCell 的 borrow_mut 若在已有其他借用時呼叫,會在執行期 panic。
簽名:
  1. Rc<RefCell<T>>
  2. pub fn borrow_mut(&self) -> RefMut<'_, T>

範例:
  1. use std::cell::RefCell;
  2. use std::rc::Rc;
  3. struct Account {
  4. owner: &'static str,
  5. log: Rc<RefCell<Vec<String>>>,
  6. }
  7. impl Account {
  8. fn act(&self, what: &str) {
  9. self.log.borrow_mut().push(format!("{} {}", self.owner, what));
  10. }
  11. }
  12. fn main() {
  13. let log = Rc::new(RefCell::new(Vec::new()));
  14. let a = Account { owner: "Amy", log: Rc::clone(&log) };
  15. let b = Account { owner: "Ben", log: Rc::clone(&log) };
  16. a.act("存款 100");
  17. b.act("提款 30");
  18. a.act("查詢餘額");
  19. for line in log.borrow().iter() {
  20. println!("{}", line);
  21. }
  22. }

輸出:
  1. Amy 存款 100
  2. Ben 提款 30
  3. Amy 查詢餘額

Weak:不擁有的參考


如果兩個 Rc 互相指向對方,計數永遠不會歸零,記憶體就洩漏了(循環參考)。Weak<T> 是弱參考:它指向資料但不算擁有者,不影響釋放。用 Rc::downgrade 從 Rc 產生 Weak,用 upgrade 嘗試取回 Rc:資料還在回傳 Some,已釋放回傳 None。
簽名:
  1. pub fn downgrade(this: &Rc<T>) -> Weak<T>
  2. pub fn upgrade(&self) -> Option<Rc<T>>
  3. pub fn weak_count(this: &Rc<T>) -> usize

範例:
  1. use std::rc::{Rc, Weak};
  2. fn main() {
  3. let weak: Weak<String>;
  4. {
  5. let strong = Rc::new(String::from("暫時的資料"));
  6. weak = Rc::downgrade(&strong);
  7. println!("strong = {}, weak = {}", Rc::strong_count(&strong), Rc::weak_count(&strong));
  8. println!("upgrade:{:?}", weak.upgrade());
  9. }
  10. println!("離開作用域後 upgrade:{:?}", weak.upgrade());
  11. }

輸出:
  1. strong = 1, weak = 1
  2. upgrade:Some("暫時的資料")
  3. 離開作用域後 upgrade:None

用 Weak 打破循環:父子樹


樹狀結構中,父節點擁有子節點(Rc),子節點只需要「知道」父節點是誰(Weak)。這樣父節點被丟掉時能正常釋放,不會形成循環。
簽名:
  1. struct Node {
  2. parent: RefCell<Weak<Node>>,
  3. children: RefCell<Vec<Rc<Node>>>,
  4. }

範例:
  1. use std::cell::RefCell;
  2. use std::rc::{Rc, Weak};
  3. struct Node {
  4. name: String,
  5. parent: RefCell<Weak<Node>>,
  6. children: RefCell<Vec<Rc<Node>>>,
  7. }
  8. impl Drop for Node {
  9. fn drop(&mut self) {
  10. println!("釋放 {}", self.name);
  11. }
  12. }
  13. fn node(name: &str) -> Rc<Node> {
  14. Rc::new(Node {
  15. name: name.to_string(),
  16. parent: RefCell::new(Weak::new()),
  17. children: RefCell::new(Vec::new()),
  18. })
  19. }
  20. fn main() {
  21. let leaf = node("leaf");
  22. {
  23. let root = node("root");
  24. *leaf.parent.borrow_mut() = Rc::downgrade(&root);
  25. root.children.borrow_mut().push(Rc::clone(&leaf));
  26. let parent_name = leaf.parent.borrow().upgrade().map(|p| p.name.clone());
  27. println!("leaf 的父節點:{:?}", parent_name);
  28. println!("root 有 {} 個子節點", root.children.borrow().len());
  29. println!("root strong = {}, weak = {}", Rc::strong_count(&root), Rc::weak_count(&root));
  30. }
  31. println!("root 已離開作用域,父節點:{:?}", leaf.parent.borrow().upgrade().map(|p| p.name.clone()));
  32. }

輸出:
  1. leaf 的父節點:Some("root")
  2. root 有 1 個子節點
  3. root strong = 1, weak = 1
  4. 釋放 root
  5. root 已離開作用域,父節點:None
  6. 釋放 leaf

try_unwrap 與 make_mut


Rc::try_unwrap 在只剩一個擁有者時取回內部值,否則把 Rc 原封不動以 Err 還給你。Rc::make_mut 提供寫入時複製(clone-on-write):只有自己一個擁有者就直接修改,否則先複製一份再改,不影響其他人。
簽名:
  1. pub fn try_unwrap(this: Rc<T>) -> Result<T, Rc<T>>
  2. pub fn make_mut(this: &mut Rc<T>) -> &mut T

範例:
  1. use std::rc::Rc;
  2. fn main() {
  3. let a = Rc::new(String::from("唯一"));
  4. println!("{:?}", Rc::try_unwrap(a));
  5. let b = Rc::new(5);
  6. let b2 = Rc::clone(&b);
  7. let back = Rc::try_unwrap(b);
  8. println!("有兩個擁有者時:is_err = {}", back.is_err());
  9. drop(back);
  10. let mut x = Rc::new(vec![1, 2]);
  11. let y = Rc::clone(&x);
  12. Rc::make_mut(&mut x).push(3);
  13. println!("x = {:?}, y = {:?}, b2 = {}", x, y, b2);
  14. }

輸出:
  1. Ok("唯一")
  2. 有兩個擁有者時:is_err = true
  3. x = [1, 2, 3], y = [1, 2], b2 = 5

重點整理


  • Rc<T> 讓多個擁有者共享資料,計數歸零才釋放
  • 用 Rc::clone(&a) 增加擁有者,只複製指標
  • 只能在單一執行緒使用,跨執行緒改用 Arc
  • 要修改共享資料,搭配 RefCell 成為 Rc<RefCell<T>>
  • 互相指向會循環洩漏,反向連結用 Weak,以 upgrade 取回