如何将字节向量(u8)转换为字符串? [英] How do I convert a Vector of bytes (u8) to a string?
本文介绍了如何将字节向量(u8)转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用 Rust 编写简单的 TCP/IP 客户端,我需要打印出我从服务器获得的缓冲区.
I am trying to write simple TCP/IP client in Rust and I need to print out the buffer I got from the server.
如何将 Vec
(或 &[u8]
)转换为 String
?
How do I convert a Vec<u8>
(or a &[u8]
) to a String
?
推荐答案
要将字节片转换为字符串片(假设为 UTF-8 编码):
To convert a slice of bytes to a string slice (assuming a UTF-8 encoding):
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()
(其他选项可用).
The conversion is in-place, and does not require an allocation. You can create a String
from the string slice if necessary by calling .to_owned()
on the string slice (other options are available).
转换函数的库参考:
这篇关于如何将字节向量(u8)转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文