繁体   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