# std::convert

型別之間互相轉換的標準特徵：`From`／`Into`、`TryFrom`／`TryInto`、`AsRef`／`AsMut`。

## 這個模組做什麼

程式裡到處都是轉換：`&str` 變 `String`、`u8` 變 `u32`、`i64` 變 `u8`（可能放不下）。如果每個型別都自己發明 `to_xxx`、`from_xxx`，使用者得一個個記。`std::convert` 統一了說法：

| 特徵 | 意義 | 會失敗嗎 | 所有權 |
| --- | --- | --- | --- |
| `From<T>`／`Into<U>` | 把值轉成另一個型別 | 不會 | 取走原值 |
| `TryFrom<T>`／`TryInto<U>` | 嘗試轉換，可能失敗 | 會，回傳 `Result` | 取走原值 |
| `AsRef<T>`／`AsMut<T>` | 便宜地「看成」另一種參考 | 不會 | 只借用 |

另外還有 `Infallible`：一個「不可能存在」的錯誤型別，用來表示永遠不會失敗的轉換。

數字之間「可能截斷」的 `as` 轉型不屬於這個模組；需要安全時改用 `TryFrom`。數值型別的細節見 [std::num](/pkg-num)。

## 匯入

`From`、`Into`、`TryFrom`、`TryInto`、`AsRef`、`AsMut` 都在 [prelude](/pkg-prelude) 裡（`TryFrom`／`TryInto` 是 Rust 2021 edition 起），不需要 `use`。`Infallible` 要自己匯入：

```rust
use std::convert::Infallible;
```

## 常用 API

### From：定義「從 T 來」的轉換

實作 `From<T> for U` 就是在說「`T` 一定能轉成 `U`」。呼叫方式是 `U::from(t)`。標準庫內建大量實作：`String::from("abc")`、`u64::from(7u32)`、`Vec::from([1, 2])`。

簽名：
```rust
pub trait From<T>: Sized {
    fn from(value: T) -> Self;
}
```

範例：
```rust
#[derive(Debug)]
struct Rgb {
    r: u8,
    g: u8,
    b: u8,
}

impl From<u32> for Rgb {
    fn from(hex: u32) -> Self {
        Rgb {
            r: (hex >> 16) as u8,
            g: (hex >> 8) as u8,
            b: hex as u8,
        }
    }
}

fn main() {
    let c = Rgb::from(0xFF8000);
    println!("{:?} 總和 {}", c, c.r as u32 + c.g as u32 + c.b as u32);
    let s = String::from("hi");
    let big = u64::from(7u32);
    let v = Vec::from([1, 2, 3]);
    println!("{} {} {:?}", s, big, v);
}
```

輸出：
```text
Rgb { r: 255, g: 128, b: 0 } 總和 383
hi 7 [1, 2, 3]
```

### Into：From 的另一面

實作了 `From<T> for U`，標準庫會自動給你 `Into<U> for T`，所以永遠只實作 `From`。`into()` 需要編譯器知道目標型別，通常寫在型別標註或函式參數上。

`impl Into<String>` 當參數型別很常見：呼叫端可以傳 `&str` 或 `String`，函式內再 `.into()`。

簽名：
```rust
pub trait Into<T>: Sized {
    fn into(self) -> T;
}
```

範例：
```rust
struct User {
    name: String,
}

impl User {
    fn new(name: impl Into<String>) -> Self {
        User { name: name.into() }
    }
}

fn main() {
    let a = User::new("amy");
    let b = User::new(String::from("ben"));
    let n: i64 = 42i32.into();
    let f: f64 = 1.5f32.into();
    println!("{} {} {} {}", a.name, b.name, n, f);
}
```

輸出：
```text
amy ben 42 1.5
```

### TryFrom 與 TryInto：可能失敗的轉換

`i32` 轉 `u8` 不一定放得下，`as` 會默默截斷（`300 as u8` 是 `44`）。`u8::try_from(300)` 則回傳 `Err`，讓你明確處理。自訂型別實作 `TryFrom` 時，用關聯型別 `Error` 指定錯誤型別；`TryInto` 同樣會自動提供。

簽名：
```rust
pub trait TryFrom<T>: Sized {
    type Error;
    fn try_from(value: T) -> Result<Self, Self::Error>;
}
```

範例：
```rust
#[derive(Debug)]
struct Percent(u8);

impl TryFrom<i32> for Percent {
    type Error = String;
    fn try_from(v: i32) -> Result<Self, Self::Error> {
        if (0..=100).contains(&v) {
            Ok(Percent(v as u8))
        } else {
            Err(format!("{} 不在 0 到 100", v))
        }
    }
}

fn main() {
    println!("{} {:?}", 300i32 as u8, u8::try_from(300i32).is_err());
    let small: Result<u8, _> = 200i32.try_into();
    println!("{:?}", small);
    if let Ok(Percent(n)) = Percent::try_from(85) {
        println!("轉換成功 {}%", n);
    }
    let p: Result<Percent, _> = 120.try_into();
    println!("{:?}", p);
}
```

輸出：
```text
44 true
Ok(200)
轉換成功 85%
Err("120 不在 0 到 100")
```

### 用 From 轉換錯誤，配合 ? 使用

`?` 遇到錯誤時會呼叫 `From::from` 把錯誤轉成函式宣告的錯誤型別。所以替錯誤型別實作 `From`，是 `From` 最常見的實際用途之一。更完整的錯誤設計見 [std::error](/pkg-error)。

範例：
```rust
use std::num::TryFromIntError;

#[derive(Debug)]
enum ConvError {
    TooLarge,
}

impl From<TryFromIntError> for ConvError {
    fn from(_: TryFromIntError) -> Self {
        ConvError::TooLarge
    }
}

fn to_byte(n: u32) -> Result<u8, ConvError> {
    let b = u8::try_from(n)?;
    Ok(b)
}

fn main() {
    println!("{:?} {:?}", to_byte(65), to_byte(1000));
}
```

輸出：
```text
Ok(65) Err(TooLarge)
```

### AsRef：接受「能看成 &T」的各種參數

`AsRef<str>` 表示「能便宜地借出一個 `&str`」。`String`、`&str`、`Box<str>` 都實作了它。把參數寫成 `impl AsRef<str>`，呼叫端什麼字串都能傳，函式內只借用，不需要複製。標準庫的 `fs::read_to_string` 就用 `AsRef<Path>` 讓你能傳 `&str`、`String` 或 `PathBuf`。

和 `Into` 的差別：`AsRef` 只借用、不產生新值；`Into` 會取走並轉成新值。

簽名：
```rust
pub trait AsRef<T: ?Sized> {
    fn as_ref(&self) -> &T;
}
```

範例：
```rust
fn shout(s: impl AsRef<str>) -> String {
    s.as_ref().to_uppercase()
}

fn total_len<T: AsRef<[u8]>>(items: &[T]) -> usize {
    items.iter().map(|x| x.as_ref().len()).sum()
}

fn main() {
    let owned = String::from("owned");
    println!("{} {}", shout("hi"), shout(&owned));
    println!("{}", shout(owned));
    println!("{}", total_len(&["ab", "cde"]));
    println!("{}", total_len(&[vec![1u8, 2], vec![3]]));
}
```

輸出：
```text
HI OWNED
OWNED
5
3
```

### AsMut：取得可變參考

`AsMut<T>` 是 `AsRef` 的可變版本，讓函式能修改各種「內部是 `[T]`」的容器，例如 `Vec<T>` 與陣列。

簽名：
```rust
pub trait AsMut<T: ?Sized> {
    fn as_mut(&mut self) -> &mut T;
}
```

範例：
```rust
fn zero_first<T: AsMut<[i32]>>(mut buf: T) -> T {
    if let Some(x) = buf.as_mut().first_mut() {
        *x = 0;
    }
    buf
}

fn main() {
    let v = zero_first(vec![5, 6, 7]);
    let a = zero_first([9, 9]);
    println!("{:?} {:?}", v, a);
}
```

輸出：
```text
[0, 6, 7] [0, 9]
```

### Infallible：永遠不會發生的錯誤

`Infallible` 是一個沒有任何成員的列舉，不可能產生它的值。`Result<T, Infallible>` 等於宣告「一定成功」。標準庫會為所有 `From` 自動實作 `TryFrom`，錯誤型別就是 `Infallible`；`String` 的 `FromStr` 也用它，因為字串轉字串不可能失敗。

因為 `Err` 分支不可能出現，可以用 `let Ok(v) = r;` 直接取值（Rust 1.82 起允許省略不可能的模式），不需要 `unwrap`。

簽名：
```rust
pub enum Infallible {}
```

範例：
```rust
use std::convert::Infallible;
use std::str::FromStr;

fn always_ok(n: i32) -> Result<i32, Infallible> {
    Ok(n * 2)
}

fn main() {
    let Ok(v) = always_ok(21);
    let r: Result<u64, Infallible> = u64::try_from(5u32);
    let s: Result<String, Infallible> = String::from_str("abc");
    println!("{} {:?} {:?}", v, r, s);
}
```

輸出：
```text
42 Ok(5) Ok("abc")
```

## 重點整理

- 只實作 `From`，`Into` 會自動提供；參數寫 `impl Into<String>` 讓呼叫端更方便
- 可能失敗用 `TryFrom`／`TryInto`，取代會默默截斷的 `as`
- `?` 透過 `From` 轉換錯誤型別，替錯誤型別實作 `From` 就能直接 `?`
- `AsRef`／`AsMut` 只借用不轉換，適合「什麼字串／切片都能收」的參數
- `Infallible` 表示不可能失敗，`Result<T, Infallible>` 可用 `let Ok(v) = ...;` 取值
