[英]How do I convert between String, &str, Vec<u8> and &[u8]?
像我这样的新 Rustacean 很难处理这些类型: String
、 &str
、 Vec<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)
str::from_utf8(u).unwrap()
有效,但您应该更喜欢更好的错误处理(请参阅错误处理 - 结果类型)。&[u8] -> String
是&[u8] -> Result<&str, Error> -> Result<String, Error>
String::from_utf8(u).unwrap()
有效,但更喜欢更好的错误处理(请参阅错误处理 - 结果类型以及Result::map
。Vec<u8>
Vec<u8> -> &[u8]
应该只是&v
在强制可用的地方,或者as_slice
在它不可用的地方。Vec<u8> -> &str
与Vec<u8> -> &[u8] -> Result<&str, Error>
即str::from_utf8(&v)
str::from_utf8(&v).unwrap()
有效,但更喜欢更好的错误处理(请参阅错误处理 - 结果类型)Vec<u8> -> String
实际上并不存在,那就是Vec<u8> -> Result<String, Error>
通过String::from_utf8(v)
String::from_utf8(v).unwrap()
有效,但更喜欢更好的错误处理(请参阅错误处理 - 结果类型)。 只要目标不是通用的,而是分别显式输入为&str
或&[u8]
,就可以使用强制转换。 Rustonomicon 有一章是关于强制的,里面有关于强制站点的更多细节。
&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.