rust中的惯用类型转换String,&str,&[u8],Vec

Conversion From To Method(s)
&str -> String &str String String::from(s), s.to_string(), s.to_owned()
&str -> &[u8] &str &[u8] s.as_bytes()
&str -> Vec &str Vec s.as_bytes().to_vec() or s.as_bytes().to_owned()
String -> &str String &str &s if possible* else s.as_str()
String -> &[u8] String &[u8] s.as_bytes()
String -> Vec String Vec s.into_bytes()
&[u8] -> &str &[u8] &str std::str::from_utf8(s).unwrap()
&[u8] -> String &[u8] String String::from_utf8(s).unwrap()
&[u8] -> Vec &[u8] Vec s.to_vec()
Vec -> &str Vec &str std::str::from_utf8(&s).unwrap()
Vec -> String Vec String String::from_utf8(s).unwrap()
Vec -> &[u8] Vec &[u8] &s if possible* else s.as_slice()

*注意:将 String 转换为 &str 或将 Vec 转换为 &str 或 &[u8] 可能会导致悬挂引用,应该确保 String 或 Vec 在生命周期内有效。