# 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（寫入時複製）的縮寫：像共用一份講義，大家都只是看時不用影印；有人要在上面寫字時，才印一份給他自己改。

## 匯入

```rust
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` 指定「擁有版本」是哪個型別。

簽名：
```rust
pub trait ToOwned {
    type Owned: Borrow<Self>;
    fn to_owned(&self) -> Self::Owned;
}
```

範例：
```rust
use std::path::Path;

fn main() {
    let s: &str = "借來的字串";
    let owned: String = s.to_owned();

    let slice: &[i32] = &[1, 2, 3];
    let v: Vec<i32> = slice.to_owned();

    let p: &Path = Path::new("/tmp/data.txt");
    let pb = p.to_owned();

    println!("{} / {:?} / {}", owned, v, pb.display());
}
```

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

### Borrow：用借用型別查詢集合

`Borrow<B>` 表示「這個型別可以借成 `&B`，而且借出來的 `&B` 在比較、雜湊上和原本完全一致」。`HashMap::get`、`BTreeMap::get`、`HashSet::contains` 都用它，所以 `HashMap<String, V>` 可以直接用 `&str` 查，不必先建一個 `String`。

簽名：
```rust
pub trait Borrow<Borrowed: ?Sized> {
    fn borrow(&self) -> &Borrowed;
}
```

範例：
```rust
use std::collections::HashMap;

fn main() {
    let mut stock: HashMap<String, u32> = HashMap::new();
    stock.insert(String::from("鉛筆"), 12);
    stock.insert(String::from("橡皮擦"), 5);

    let query: &str = "鉛筆";
    println!("{} 還有 {:?} 支", query, stock.get(query));

    let ids: Vec<Vec<u8>> = vec![vec![1, 2], vec![3]];
    let wanted: &[u8] = &[3];
    println!("找到 [3]：{}", ids.iter().any(|v| v.as_slice() == wanted));
}
```

輸出：
```text
鉛筆 還有 Some(12) 支
找到 [3]：true
```

### 自己寫接受 Borrow 的泛型函式

在函式參數用 `T: Borrow<str>`，呼叫端就能傳 `String`、`&str`，甚至 `&String`，函式內統一用 `.borrow()` 取得 `&str`。因為一個型別可能同時實作多個 `Borrow<X>`，呼叫時常需要標註結果型別（如 `let s: &str = ...`）讓編譯器知道要哪一個。

注意：實作 `Borrow` 時，`Eq`、`Ord`、`Hash` 的結果必須和被借出的型別一致，否則集合查詢會出錯；只是想「轉成參考」而沒有這個保證時，應該用 `AsRef`（見 [std::convert](/pkg-convert)）。

簽名：
```rust
fn borrow(&self) -> &Borrowed
```

範例：
```rust
use std::borrow::Borrow;

fn count_long<T: Borrow<str>>(words: &[T]) -> usize {
    words
        .iter()
        .filter(|w| {
            let s: &str = (**w).borrow();
            s.chars().count() > 3
        })
        .count()
}

fn main() {
    let owned = vec![String::from("rust"), String::from("go"), String::from("python")];
    let borrowed = ["c", "java", "kotlin", "zig"];

    println!("String 陣列：{}", count_long(&owned));
    println!("&str 陣列：{}", count_long(&borrowed));
}
```

輸出：
```text
String 陣列：2
&str 陣列：2
```

### Cow：可能借用、可能擁有

`Cow<'a, B>` 是一個列舉，有兩個變體：`Cow::Borrowed(&'a B)` 與 `Cow::Owned(B::Owned)`。函式回傳 `Cow` 可以在「不需要改」時直接回傳借用，零配置；只有真的修改時才配置新的字串。

簽名：
```rust
pub enum Cow<'a, B: ?Sized + 'a>
where
    B: ToOwned,
{
    Borrowed(&'a B),
    Owned(<B as ToOwned>::Owned),
}
```

範例：
```rust
use std::borrow::Cow;

fn escape_html(input: &str) -> Cow<'_, str> {
    if !input.contains(['<', '>', '&']) {
        return Cow::Borrowed(input);
    }
    let mut out = String::with_capacity(input.len() + 8);
    for ch in input.chars() {
        match ch {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            c => out.push(c),
        }
    }
    Cow::Owned(out)
}

fn main() {
    for text in ["你好", "a < b && c"] {
        let r = escape_html(text);
        let kind = match &r {
            Cow::Borrowed(_) => "借用",
            Cow::Owned(_) => "新配置",
        };
        println!("{} -> {}（{}）", text, r, kind);
    }
}
```

輸出：
```text
你好 -> 你好（借用）
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` 判斷狀態。

簽名：
```rust
pub fn to_mut(&mut self) -> &mut <B as ToOwned>::Owned
```

範例：
```rust
use std::borrow::Cow;

fn state(c: &Cow<'_, [i32]>) -> &'static str {
    match c {
        Cow::Borrowed(_) => "Borrowed",
        Cow::Owned(_) => "Owned",
    }
}

fn main() {
    let data = [3, -1, 4, -5];
    let mut c: Cow<[i32]> = Cow::Borrowed(&data);
    println!("開始：{}", state(&c));

    for i in 0..c.len() {
        if c[i] < 0 {
            c.to_mut()[i] = 0;
        }
    }
    println!("修改後：{} {:?}", state(&c), c);
    println!("原陣列不變：{:?}", data);
}
```

輸出：
```text
開始：Borrowed
修改後：Owned [3, 0, 4, 0]
原陣列不變：[3, -1, 4, -5]
```

### into_owned：最後一定要擁有

`into_owned` 消耗 `Cow` 並回傳擁有的值：已是 `Owned` 直接取出，是 `Borrowed` 才複製。適合處理流程最後要存進結構或回傳給呼叫端時。`Cow` 也實作了 `From`，可以用 `.into()` 從 `&str` 或 `String` 建立。

簽名：
```rust
pub fn into_owned(self) -> <B as ToOwned>::Owned
```

範例：
```rust
use std::borrow::Cow;

struct Message {
    text: String,
}

fn normalize(s: &str) -> Cow<'_, str> {
    if s.ends_with('。') {
        s.into()
    } else {
        format!("{}。", s).into()
    }
}

fn main() {
    let a = Message { text: normalize("已完成。").into_owned() };
    let b = Message { text: normalize("處理中").into_owned() };
    println!("{}", a.text);
    println!("{}", b.text);
}
```

輸出：
```text
已完成。
處理中。
```

### Cow 當結構欄位

把 `Cow<'a, str>` 放進結構，可以讓同一個型別同時容納「指向常數字串的預設值」與「執行期組出來的字串」，不必為了統一型別而把所有常數都 `to_string()`。

簽名：
```rust
struct Label<'a> {
    text: Cow<'a, str>,
}
```

範例：
```rust
use std::borrow::Cow;

struct Label<'a> {
    text: Cow<'a, str>,
}

impl<'a> Label<'a> {
    fn fixed(s: &'a str) -> Self {
        Label { text: Cow::Borrowed(s) }
    }
    fn counted(n: u32) -> Self {
        Label { text: Cow::Owned(format!("第 {} 項", n)) }
    }
}

fn main() {
    let labels = vec![Label::fixed("標題"), Label::counted(1), Label::counted(2)];
    let joined: Vec<&str> = labels.iter().map(|l| l.text.as_ref()).collect();
    println!("{}", joined.join(" | "));
}
```

輸出：
```text
標題 | 第 1 項 | 第 2 項
```

## 重點整理

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