簡體   English   中英

如何在字符串、&amp;str、Vec 之間進行轉換<u8>和 &amp;[u8]?

[英]How do I convert between String, &str, Vec<u8> and &[u8]?

像我這樣的新 Rustacean 很難處理這些類型: String&strVec<u8>&[u8]

隨着時間的推移,我希望有一個頓悟,突然明白為什么有些庫調用使用其中一個。 在那之前,我需要幫助來繪制每個慣用的轉換。

鑒於這些類型:

let st: &str = ...;
let s:  String = ...;
let u:  &[u8] = ...;
let v:  Vec<u8> = ...;

我想我已經弄清楚了,但它們是慣用的嗎?

&str    -> String    String::from(st)
&str    -> &[u8]     st.as_bytes()
String  -> &str      s.as_str()
&[u8]   -> &str      str::from_utf8(u)
Vec<u8> -> String    String::from_utf8(v)

最終,我想要這些類型的完整轉換表:

&str    -> String
&str    -> &[u8]
&str    -> Vec<u8>
String  -> &str
String  -> &[u8]
String  -> Vec<u8>
&[u8]   -> &str
&[u8]   -> String
&[u8]   -> Vec<u8>
Vec<u8> -> &str
Vec<u8> -> String
Vec<u8> -> &[u8]

&str

  • &str -> String許多同樣有效的方法String::from(st)st.to_string()st.to_owned()
    • 但我建議您在單個項目中堅持使用其中之一。 String::from的主要優點是您可以將其用作map方法的參數。 因此,您可以經常使用x.map(String::from)代替x.map(|s| String::from(s)) x.map(String::from)
  • &str -> &[u8]st.as_bytes()
  • &str -> Vec<u8>&str -> &[u8] -> Vec<u8> ,即st.as_bytes().to_vec()st.as_bytes().to_owned()

String

  • String -> &str應該只是&s在強制可用&s地方或s.as_str()在它不可用的地方。
  • String -> &[u8]&str -> &[u8] : s.as_bytes()
  • String -> Vec<u8>有一個自定義方法: s.into_bytes()

來自&[u8]

  • &[u8] -> Vec<u8>u.to_owned()u.to_vec() 它們做同樣的事情,但to_vec有一個輕微的優勢,即它返回的類型是明確的。
  • &[u8] -> &str實際上並不存在,即&[u8] -> Result<&str, Error> ,通過str::from_utf8(u)
  • &[u8] -> String&[u8] -> Result<&str, Error> -> Result<String, Error>

來自Vec<u8>

  • Vec<u8> -> &[u8]應該只是&v在強制可用的地方,或者as_slice在它不可用的地方。
  • Vec<u8> -> &strVec<u8> -> &[u8] -> Result<&str, Error>str::from_utf8(&v)
  • Vec<u8> -> String實際上並不存在,那就是Vec<u8> -> Result<String, Error>通過String::from_utf8(v)

只要目標不是通用的,而是分別顯式輸入為&str&[u8] ,就可以使用強制轉換。 Rustonomicon 有一章是關於強制的,里面有關於強制站點的更多細節。


tl;博士

&str    -> String  | String::from(s) or s.to_string() or s.to_owned()
&str    -> &[u8]   | s.as_bytes()
&str    -> Vec<u8> | s.as_bytes().to_vec() or s.as_bytes().to_owned()
String  -> &str    | &s if possible* else s.as_str()
String  -> &[u8]   | s.as_bytes()
String  -> Vec<u8> | s.into_bytes()
&[u8]   -> &str    | s.to_vec() or s.to_owned()
&[u8]   -> String  | std::str::from_utf8(s).unwrap(), but don't**
&[u8]   -> Vec<u8> | String::from_utf8(s).unwrap(), but don't**
Vec<u8> -> &str    | &s if possible* else s.as_slice()
Vec<u8> -> String  | std::str::from_utf8(&s).unwrap(), but don't**
Vec<u8> -> &[u8]   | String::from_utf8(s).unwrap(), but don't**

* target should have explicit type (i.e., checker can't infer that)

** handle the error properly instead

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM