问题描述
这是我的代码:
let mut altbuf: Vec<u8> = Vec::new();
// Stuff here...
match stream.read_byte() {
Ok(d) => altbuf.push(d),
Err(e) => { println!("Error: {}", e); doneflag = true; }
}
for x in altbuf.iter() {
println!("{}", x);
}
代码打印 u8 字节是正确的,但我终生不知道如何将纯 u8 字节向量转换为字符串?关于堆栈溢出的类似问题的唯一其他答案假定您正在使用类型为 &[u8] 的向量.
The code prints u8 bytes which are correct, but I can't figure out for the life of me how to convert a vector of pure u8 bytes into a string? The only other answer to a similar question on stack overflow assumes that you're working with a vector of type &[u8].
推荐答案
如果你看一下 String
文档,您可以使用一些方法.有 String::from_utf8
需要一个 Vec
,还有 String::from_utf8_lossy
需要一个 &[u8]
.
If you look at the String
documentation, there are a few methods you could use. There's String::from_utf8
that takes a Vec<u8>
, and there's also String::from_utf8_lossy
which takes a &[u8]
.
请注意,Vec
或多或少是 [T]
周围的一个拥有的、可调整大小的包装器.也就是说,如果你有一个 Vec
,你可以把它变成一个 &[u8]
,最简单的方法是重新借用它(ie &*some_vec
).您还可以直接在 Vec
上调用任何定义在 &[T]
上的方法(通常,实现 Deref
trait).
Note that a Vec<T>
is more-or-less an owned, resizable wrapper around a [T]
. That is, if you have a Vec<u8>
, you can turn it into a &[u8]
, most easily by re-borrowing it (i.e. &*some_vec
). You can also call any methods defined on &[T]
directly on a Vec<T>
(in general, this is true of things that implement the Deref
trait).
这篇关于如何将 u8 的向量打印为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!