std::borrow

最後更新


處理「借用版本」與「擁有版本」之間轉換的工具:Borrow、ToOwned 特徵與寫入時複製的 Cow。

這個模組做什麼


很多型別成對出現:String 與 &str、Vec<T> 與 &[T]、PathBuf 與 &Path。前者擁有資料(owned),後者只是借來看(borrowed)。這個模組回答三個問題:
問題工具例子
擁有型別能不能「當成」借用型別來比較、查詢?Borrow<B> 特徵HashMap<String, _> 用 &str 查詢
怎麼從借用型別做出一份擁有的副本?ToOwned 特徵"abc".to_owned() 得到 String
大多數時候只讀、偶爾才要修改,能不能省下複製?Cow<'a, B>沒有需要跳脫的字元就直接回傳原字串

Cow 是 Clone-on-Write(寫入時複製)的縮寫:像共用一份講義,大家都只是看時不用影印;有人要在上面寫字時,才印一份給他自己改。

匯入


  1. use std::borrow::{Borrow, Cow};

ToOwned 已在 prelude 中(完整路徑 std::borrow::ToOwned),直接呼叫 .to_owned() 即可。Borrow、BorrowMut 與 Cow 需要 use。

常用 API


ToOwned:從借用做出擁有的副本


Clone 只能從 &T 複製出 T;但 &str 複製出來應該是 String 而不是 str(str 沒有固定大小,不能單獨存在)。ToOwned 就是更一般化的 Clone:它用關聯型別 Owned 指定「擁有版本」是哪個型別。
簽名:
  1. pub trait ToOwned {
  2. type Owned: Borrow<Self>;
  3. fn to_owned(&self) -> Self::Owned;
  4. }

範例:
  1. use std::path::Path;
  2. fn main() {
  3. let s: &str = "借來的字串";
  4. let owned: String = s.to_owned();
  5. let slice: &[i32] = &[1, 2, 3];
  6. let v: Vec<i32> = slice.to_owned();
  7. let p: &Path = Path::new("/tmp/data.txt");
  8. let pb = p.to_owned();
  9. println!("{} / {:?} / {}", owned, v, pb.display());
  10. }

輸出:
  1. 借來的字串 / [1, 2, 3] / /tmp/data.txt

Borrow:用借用型別查詢集合


Borrow<B> 表示「這個型別可以借成 &B,而且借出來的 &B 在比較、雜湊上和原本完全一致」。HashMap::get、BTreeMap::get、HashSet::contains 都用它,所以 HashMap<String, V> 可以直接用 &str 查,不必先建一個 String。
簽名:
  1. pub trait Borrow<Borrowed: ?Sized> {
  2. fn borrow(&self) -> &Borrowed;
  3. }

範例:
  1. use std::collections::HashMap;
  2. fn main() {
  3. let mut stock: HashMap<String, u32> = HashMap::new();
  4. stock.insert(String::from("鉛筆"), 12);
  5. stock.insert(String::from("橡皮擦"), 5);
  6. let query: &str = "鉛筆";
  7. println!("{} 還有 {:?} 支", query, stock.get(query));
  8. let ids: Vec<Vec<u8>> = vec![vec![1, 2], vec![3]];
  9. let wanted: &[u8] = &[3];
  10. println!("找到 [3]:{}", ids.iter().any(|v| v.as_slice() == wanted));
  11. }

輸出:
  1. 鉛筆 還有 Some(12) 支
  2. 找到 [3]:true

自己寫接受 Borrow 的泛型函式


在函式參數用 T: Borrow<str>,呼叫端就能傳 String、&str,甚至 &String,函式內統一用 .borrow() 取得 &str。因為一個型別可能同時實作多個 Borrow<X>,呼叫時常需要標註結果型別(如 let s: &str = ...)讓編譯器知道要哪一個。
注意:實作 Borrow 時,Eq、Ord、Hash 的結果必須和被借出的型別一致,否則集合查詢會出錯;只是想「轉成參考」而沒有這個保證時,應該用 AsRef(見 std::convert)。
簽名:
  1. fn borrow(&self) -> &Borrowed

範例:
  1. use std::borrow::Borrow;
  2. fn count_long<T: Borrow<str>>(words: &[T]) -> usize {
  3. words
  4. .iter()
  5. .filter(|w| {
  6. let s: &str = (**w).borrow();
  7. s.chars().count() > 3
  8. })
  9. .count()
  10. }
  11. fn main() {
  12. let owned = vec![String::from("rust"), String::from("go"), String::from("python")];
  13. let borrowed = ["c", "java", "kotlin", "zig"];
  14. println!("String 陣列:{}", count_long(&owned));
  15. println!("&str 陣列:{}", count_long(&borrowed));
  16. }

輸出:
  1. String 陣列:2
  2. &str 陣列:2

Cow:可能借用、可能擁有


Cow<'a, B> 是一個列舉,有兩個變體:Cow::Borrowed(&'a B) 與 Cow::Owned(B::Owned)。函式回傳 Cow 可以在「不需要改」時直接回傳借用,零配置;只有真的修改時才配置新的字串。
簽名:
  1. pub enum Cow<'a, B: ?Sized + 'a>
  2. where
  3. B: ToOwned,
  4. {
  5. Borrowed(&'a B),
  6. Owned(<B as ToOwned>::Owned),
  7. }

範例:
  1. use std::borrow::Cow;
  2. fn escape_html(input: &str) -> Cow<'_, str> {
  3. if !input.contains(['<', '>', '&']) {
  4. return Cow::Borrowed(input);
  5. }
  6. let mut out = String::with_capacity(input.len() + 8);
  7. for ch in input.chars() {
  8. match ch {
  9. '<' => out.push_str("&lt;"),
  10. '>' => out.push_str("&gt;"),
  11. '&' => out.push_str("&amp;"),
  12. c => out.push(c),
  13. }
  14. }
  15. Cow::Owned(out)
  16. }
  17. fn main() {
  18. for text in ["你好", "a < b && c"] {
  19. let r = escape_html(text);
  20. let kind = match &r {
  21. Cow::Borrowed(_) => "借用",
  22. Cow::Owned(_) => "新配置",
  23. };
  24. println!("{} -> {}({})", text, r, kind);
  25. }
  26. }

輸出:
  1. 你好 -> 你好(借用)
  2. a < b && c -> a &lt; b &amp;&amp; c(新配置)

Cow<str> 實作了 Deref<Target = str>,所以可以像 &str 一樣直接印出或呼叫字串方法。

to_mut:要寫入時才複製


Cow::to_mut 取得內部資料的可變參考。若目前是 Borrowed,會先 to_owned 複製一份並切換成 Owned;若已經是 Owned,就直接回傳,不再複製。is_borrowed/is_owned 尚未穩定,這裡用 match 判斷狀態。
簽名:
  1. pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned

範例:
  1. use std::borrow::Cow;
  2. fn state(c: &Cow<'_, [i32]>) -> &'static str {
  3. match c {
  4. Cow::Borrowed(_) => "Borrowed",
  5. Cow::Owned(_) => "Owned",
  6. }
  7. }
  8. fn main() {
  9. let data = [3, -1, 4, -5];
  10. let mut c: Cow<[i32]> = Cow::Borrowed(&data);
  11. println!("開始:{}", state(&c));
  12. for i in 0..c.len() {
  13. if c[i] < 0 {
  14. c.to_mut()[i] = 0;
  15. }
  16. }
  17. println!("修改後:{} {:?}", state(&c), c);
  18. println!("原陣列不變:{:?}", data);
  19. }

輸出:
  1. 開始:Borrowed
  2. 修改後:Owned [3, 0, 4, 0]
  3. 原陣列不變:[3, -1, 4, -5]

into_owned:最後一定要擁有


into_owned 消耗 Cow 並回傳擁有的值:已是 Owned 直接取出,是 Borrowed 才複製。適合處理流程最後要存進結構或回傳給呼叫端時。Cow 也實作了 From,可以用 .into() 從 &str 或 String 建立。
簽名:
  1. pub fn into_owned(self) -> <B as ToOwned>::Owned

範例:
  1. use std::borrow::Cow;
  2. struct Message {
  3. text: String,
  4. }
  5. fn normalize(s: &str) -> Cow<'_, str> {
  6. if s.ends_with('。') {
  7. s.into()
  8. } else {
  9. format!("{}。", s).into()
  10. }
  11. }
  12. fn main() {
  13. let a = Message { text: normalize("已完成。").into_owned() };
  14. let b = Message { text: normalize("處理中").into_owned() };
  15. println!("{}", a.text);
  16. println!("{}", b.text);
  17. }

輸出:
  1. 已完成。
  2. 處理中。

Cow 當結構欄位


把 Cow<'a, str> 放進結構,可以讓同一個型別同時容納「指向常數字串的預設值」與「執行期組出來的字串」,不必為了統一型別而把所有常數都 to_string()。
簽名:
  1. struct Label<'a> {
  2. text: Cow<'a, str>,
  3. }

範例:
  1. use std::borrow::Cow;
  2. struct Label<'a> {
  3. text: Cow<'a, str>,
  4. }
  5. impl<'a> Label<'a> {
  6. fn fixed(s: &'a str) -> Self {
  7. Label { text: Cow::Borrowed(s) }
  8. }
  9. fn counted(n: u32) -> Self {
  10. Label { text: Cow::Owned(format!("第 {} 項", n)) }
  11. }
  12. }
  13. fn main() {
  14. let labels = vec![Label::fixed("標題"), Label::counted(1), Label::counted(2)];
  15. let joined: Vec<&str> = labels.iter().map(|l| l.text.as_ref()).collect();
  16. println!("{}", joined.join(" | "));
  17. }

輸出:
  1. 標題 | 第 1 項 | 第 2 項

重點整理


  • ToOwned 是一般化的 Clone:&str → String、&[T] → Vec<T>
  • Borrow 讓集合能用借用型別查詢,例如 HashMap<String, _> 用 &str 查
  • 實作 Borrow 必須保持比較與雜湊一致,只想轉參考就用 AsRef
  • Cow 在不需要修改時零複製,to_mut 第一次寫入才複製
  • into_owned 取得擁有的值,Borrowed 時才會配置