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。

匯入


From、Into、TryFrom、TryInto、AsRef、AsMut 都在 prelude 裡(TryFrom/TryInto 是 Rust 2021 edition 起),不需要 use。Infallible 要自己匯入:
  1. 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])。
簽名:
  1. pub trait From<T>: Sized {
  2. fn from(value: T) -> Self;
  3. }

範例:
  1. #[derive(Debug)]
  2. struct Rgb {
  3. r: u8,
  4. g: u8,
  5. b: u8,
  6. }
  7. impl From<u32> for Rgb {
  8. fn from(hex: u32) -> Self {
  9. Rgb {
  10. r: (hex >> 16) as u8,
  11. g: (hex >> 8) as u8,
  12. b: hex as u8,
  13. }
  14. }
  15. }
  16. fn main() {
  17. let c = Rgb::from(0xFF8000);
  18. println!("{:?} 總和 {}", c, c.r as u32 + c.g as u32 + c.b as u32);
  19. let s = String::from("hi");
  20. let big = u64::from(7u32);
  21. let v = Vec::from([1, 2, 3]);
  22. println!("{} {} {:?}", s, big, v);
  23. }

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

Into:From 的另一面


實作了 From<T> for U,標準庫會自動給你 Into<U> for T,所以永遠只實作 From。into() 需要編譯器知道目標型別,通常寫在型別標註或函式參數上。
impl Into<String> 當參數型別很常見:呼叫端可以傳 &str 或 String,函式內再 .into()。
簽名:
  1. pub trait Into<T>: Sized {
  2. fn into(self) -> T;
  3. }

範例:
  1. struct User {
  2. name: String,
  3. }
  4. impl User {
  5. fn new(name: impl Into<String>) -> Self {
  6. User { name: name.into() }
  7. }
  8. }
  9. fn main() {
  10. let a = User::new("amy");
  11. let b = User::new(String::from("ben"));
  12. let n: i64 = 42i32.into();
  13. let f: f64 = 1.5f32.into();
  14. println!("{} {} {} {}", a.name, b.name, n, f);
  15. }

輸出:
  1. amy ben 42 1.5

TryFrom 與 TryInto:可能失敗的轉換


i32 轉 u8 不一定放得下,as 會默默截斷(300 as u8 是 44)。u8::try_from(300) 則回傳 Err,讓你明確處理。自訂型別實作 TryFrom 時,用關聯型別 Error 指定錯誤型別;TryInto 同樣會自動提供。
簽名:
  1. pub trait TryFrom<T>: Sized {
  2. type Error;
  3. fn try_from(value: T) -> Result<Self, Self::Error>;
  4. }

範例:
  1. #[derive(Debug)]
  2. struct Percent(u8);
  3. impl TryFrom<i32> for Percent {
  4. type Error = String;
  5. fn try_from(v: i32) -> Result<Self, Self::Error> {
  6. if (0..=100).contains(&v) {
  7. Ok(Percent(v as u8))
  8. } else {
  9. Err(format!("{} 不在 0 到 100", v))
  10. }
  11. }
  12. }
  13. fn main() {
  14. println!("{} {:?}", 300i32 as u8, u8::try_from(300i32).is_err());
  15. let small: Result<u8, _> = 200i32.try_into();
  16. println!("{:?}", small);
  17. if let Ok(Percent(n)) = Percent::try_from(85) {
  18. println!("轉換成功 {}%", n);
  19. }
  20. let p: Result<Percent, _> = 120.try_into();
  21. println!("{:?}", p);
  22. }

輸出:
  1. 44 true
  2. Ok(200)
  3. 轉換成功 85%
  4. Err("120 不在 0 到 100")

用 From 轉換錯誤,配合 ? 使用


? 遇到錯誤時會呼叫 From::from 把錯誤轉成函式宣告的錯誤型別。所以替錯誤型別實作 From,是 From 最常見的實際用途之一。更完整的錯誤設計見 std::error。
範例:
  1. use std::num::TryFromIntError;
  2. #[derive(Debug)]
  3. enum ConvError {
  4. TooLarge,
  5. }
  6. impl From<TryFromIntError> for ConvError {
  7. fn from(_: TryFromIntError) -> Self {
  8. ConvError::TooLarge
  9. }
  10. }
  11. fn to_byte(n: u32) -> Result<u8, ConvError> {
  12. let b = u8::try_from(n)?;
  13. Ok(b)
  14. }
  15. fn main() {
  16. println!("{:?} {:?}", to_byte(65), to_byte(1000));
  17. }

輸出:
  1. 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 會取走並轉成新值。
簽名:
  1. pub trait AsRef<T: ?Sized> {
  2. fn as_ref(&self) -> &T;
  3. }

範例:
  1. fn shout(s: impl AsRef<str>) -> String {
  2. s.as_ref().to_uppercase()
  3. }
  4. fn total_len<T: AsRef<[u8]>>(items: &[T]) -> usize {
  5. items.iter().map(|x| x.as_ref().len()).sum()
  6. }
  7. fn main() {
  8. let owned = String::from("owned");
  9. println!("{} {}", shout("hi"), shout(&owned));
  10. println!("{}", shout(owned));
  11. println!("{}", total_len(&["ab", "cde"]));
  12. println!("{}", total_len(&[vec![1u8, 2], vec![3]]));
  13. }

輸出:
  1. HI OWNED
  2. OWNED
  3. 5
  4. 3

AsMut:取得可變參考


AsMut<T> 是 AsRef 的可變版本,讓函式能修改各種「內部是 [T]」的容器,例如 Vec<T> 與陣列。
簽名:
  1. pub trait AsMut<T: ?Sized> {
  2. fn as_mut(&mut self) -> &mut T;
  3. }

範例:
  1. fn zero_first<T: AsMut<[i32]>>(mut buf: T) -> T {
  2. if let Some(x) = buf.as_mut().first_mut() {
  3. *x = 0;
  4. }
  5. buf
  6. }
  7. fn main() {
  8. let v = zero_first(vec![5, 6, 7]);
  9. let a = zero_first([9, 9]);
  10. println!("{:?} {:?}", v, a);
  11. }

輸出:
  1. [0, 6, 7] [0, 9]

Infallible:永遠不會發生的錯誤


Infallible 是一個沒有任何成員的列舉,不可能產生它的值。Result<T, Infallible> 等於宣告「一定成功」。標準庫會為所有 From 自動實作 TryFrom,錯誤型別就是 Infallible;String 的 FromStr 也用它,因為字串轉字串不可能失敗。
因為 Err 分支不可能出現,可以用 let Ok(v) = r; 直接取值(Rust 1.82 起允許省略不可能的模式),不需要 unwrap。
簽名:
  1. pub enum Infallible {}

範例:
  1. use std::convert::Infallible;
  2. use std::str::FromStr;
  3. fn always_ok(n: i32) -> Result<i32, Infallible> {
  4. Ok(n * 2)
  5. }
  6. fn main() {
  7. let Ok(v) = always_ok(21);
  8. let r: Result<u64, Infallible> = u64::try_from(5u32);
  9. let s: Result<String, Infallible> = String::from_str("abc");
  10. println!("{} {:?} {:?}", v, r, s);
  11. }

輸出:
  1. 42 Ok(5) Ok("abc")

重點整理


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