关于rust:如何将字节向量(u8)转换为字符串

How do I convert a Vector of bytes (u8) to a string

我试图在Rust中编写简单的TCP / IP客户端,我需要打印出从服务器获得的缓冲区。

如何将Vec(或&[u8])转换为String


要将字节片转换为字符串片(假设采用UTF-8编码):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::str;

//
// pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error>
//
// Assuming buf: &[u8]
//

fn main() {

    let buf = &[0x41u8, 0x41u8, 0x42u8];

    let s = match str::from_utf8(buf) {
        Ok(v) => v,
        Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
    };

    println!("result: {}", s);
}

转换是就地的,不需要分配。 您可以根据需要通过在字符串切片上调用.to_owned()从字符串切片创建String(其他选项可用)。

转换功能的库参考:

  • std::str::from_utf8


我更喜欢String::from_utf8_lossy

1
2
3
4
5
fn main() {
    let buf = &[0x41u8, 0x41u8, 0x42u8];
    let s = String::from_utf8_lossy(buf);
    println!("result: {}", s);
}

它将无效的UTF-8字节转换为? 因此不需要错误处理。 当您不需要它而我几乎不需要它时,它非常有用。 您实际上从中得到一个String。 它应该使打印从服务器上获得的内容变得容易一些。

有时您可能需要使用into_owned()方法,因为它是在写入时克隆的。


如果您实际上有一个字节向量(Vec)并想转换为String,最有效的方法是使用String::from_utf8重用分配:

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