[英]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.