rust字节数组转换为string

一、String::from_utf8

fn main() {
    let bytes = vec![0x41, 0x42, 0x43];
    let s = String::from_utf8(bytes).expect("Found invalid UTF-8");
    println!("{}", s);
}

二、String::from_utf8_lossy

fn main() {
    let buf = &[0x41u8, 0x41u8, 0x42u8];
    let s = String::from_utf8_lossy(buf);
    println!("result: {}", s);
}
posted @ 2021-11-18 11:31  hziwei  阅读(2798)  评论(0编辑  收藏  举报