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]的惯用转换
from | to | 函数 |
---|---|---|
&str | String | String::from(s) 或 s.to_string() 或 s.to_owned() |
&str | &[u8] | s.as_bytes() |
&str | Vec | s.as_bytes().to_vec() |
String | &[u8] | s.as_bytes() |
String | &str | s.as_str() 或 &s |
String | Vec | s.into_bytes() |
&[u8] | &str | std::str::from_utf8(s).unwrap() |
&[u8] | String | String::from_utf8(s).unwrap() |
&[u8] | Vec | s.to_vec() |
Vec | &str | std::str::from_utf8(&s).unwrap() |
Vec | String | String::from_utf8(s).unwrap() String::from_utf8(s).unwrap()? |
Vec | &[u8] | &s 或 s.as_slice() |