加入收藏 | 设为首页 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > 学习资料

rust中String,&str,Vec <u8>和&[u8]的惯用转换

时间:2023-02-12 19:36:00  来源:原创  作者:站长
&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>
 

主要作用为:将字节数组转换为字符串。bWn华陈数据科技
Converts a slice of bytes to a string slice.bWn华陈数据科技

并不是所有的字节数组都有相应的字符串表示,返回值为&str表示为有UTF-8字节数组对应的有效字符串;返回值为Utf8Error表示不具有有效的字符串表示。若不需要判断是否有有效的字符串表示,可用from_utf8_unchecked来实现。bWn华陈数据科技

as_bytes()函数

pub fn as_bytes(&self) -> &[u8]
bWn华陈数据科技
将字符串转换为字节数组。若需再将字符数组转化为字符串,可借助上面提到的str::from_utf8函数。bWn华陈数据科技
bWn华陈数据科技
 
来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
实现php间隔一段时间执行一次某段代码
实现php间隔一段时间
相关文章
    无相关信息
栏目更新
栏目热门