下面的代码可以跑,就不知道除了取指针和 len 重新构造,还没有代码更少的方式?
use std::slice;
use std::str;
fn main() {
let mut s = [0 as u8; 12];
s[0] = b'h';
s[1] = b'e';
s[2] = b'l';
s[3] = b'l';
s[4] = b'o';
println!("{:?}", &s[..5]);
let s1 = unsafe {
let slice = slice::from_raw_parts(s.as_ptr(), s.len());
str::from_utf8(slice)
};
println!("{}", s1.unwrap());
}
1
lyy16384 2019-11-05 10:40:45 +08:00 1
对 s 取引用就是一个 slice,不需要通过 slice::from_raw_parts 再构造一遍
use std::str; fn main() { let mut s = [0 as u8; 12]; s[0] = b'h'; s[1] = b'e'; s[2] = b'l'; s[3] = b'l'; s[4] = b'o'; let s1 = str::from_utf8(&s); println!("{}", s1.unwrap()); } |
2
guonaihong OP @lyy16384 谢了。
|