rust将json字符串转换为字节数组
rust中String,&str,Vec
https://zhuanlan.zhihu.com/p/372082802
&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**
std::str::from_utf8
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
主要作用为:将字节数组转换为字符串。
Converts a slice of bytes to a string slice.
并不是所有的字节数组都有相应的字符串表示,返回值为&str表示为有UTF-8字节数组对应的有效字符串;返回值为Utf8Error表示不具有有效的字符串表示。若不需要判断是否有有效的字符串表示,可用from_utf8_unchecked来实现。
as_bytes()函数
pub fn as_bytes(&self) -> &[u8]
将字符串转换为字节数组。若需再将字符数组转化为字符串,可借助上面提到的str::from_utf8函数。

浙公网安备 33010602011771号