rust 中实用转换

How to convert a &str to a &[u8]

c语言中u8,u16,u32和int区别
一、符号不同
1、u8:u8表示无符号char字符类型。
2、u16:u16表示无符号short短整数类型。
3、u32:u32表示无符号int基本整数类型。
4、int:int表示带符号int基本整数类型。
二、数据范围不同
1、u8:u8的数据范围为0~+127[0~2^8-1]。
2、u16:u16的数据范围为0~+65535[0~2^16-1]。
3、u32:u32的数据范围为0+2147483647[02^32-1]。
4、int:int的数据范围为-2147483648~+2147483647[-2^31~2^31-1]。
三、内存占用空间不同
1、u8:u8的内存占用空间大小为只占一个字节。
2、u16:u16的内存占用空间大小为占用两个字节。
3、u32:u32的内存占用空间大小为占用四个字节。
4、int:int的内存占用空间大小为占用八个字节。

You can use the as_bytes method:

fn f(s: &[u8]) {}

pub fn main() {
    let x = "a";
    f(x.as_bytes())
}
fn main() {
    let buffer: [u8; 9] = [255, 255, 255, 255, 77, 80, 81, 82, 83];
    let s = std::str::from_utf8(&buffer[5..9]).expect("invalid utf-8 sequence");
    println!("{}", s);
    assert_eq!("PQRS", s);
}

String,&str,Vec 和&[u8]的惯用转换

fromto函数
&strStringString::from(s) 或 s.to_string() 或 s.to_owned()
&str&[u8]s.as_bytes()
&strVecs.as_bytes().to_vec()
String&[u8]s.as_bytes()
String&strs.as_str() 或 &s
StringVecs.into_bytes()
&[u8]&strstd::str::from_utf8(s).unwrap()
&[u8]StringString::from_utf8(s).unwrap()
&[u8]Vecs.to_vec()
Vec&strstd::str::from_utf8(&s).unwrap()
VecStringString::from_utf8(s).unwrap() String::from_utf8(s).unwrap()?
Vec&[u8]&s 或 s.as_slice()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值