【发布时间】:2016-10-28 14:47:30
【问题描述】:
Hyper 具有 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> 功能,可将 HTTP 响应的内容读取到提供的 &mut [u8] 中。
Flate2 可以gunzip:
let mut d = GzDecoder::new("...".as_bytes()).unwrap();
let mut s = String::new();
d.read_to_string(&mut s).unwrap();
println!("{}", s);
我试着把这两件事放在一起:
fn gunzip(r: &Response) -> String {
let mut zs: &mut [u8] = &mut[];
r.read(zs);
let mut d = GzDecoder::new(zs).unwrap();
let mut s = String::new();
d.read_to_string(&mut s).unwrap();
s
}
我得到了错误:
error[E0277]: the trait bound `[u8]: std::io::Read` is not satisfied
--> tests/integration.rs:232:21
|
232 | let mut d = GzDecoder::new(zs).unwrap();
| ^^^^^^^^^^^^^^ trait `[u8]: std::io::Read` not satisfied
|
= help: the following implementations were found:
= help: <&'a [u8] as std::io::Read>
= note: required because of the requirements on the impl of `std::io::Read` for `&mut [u8]`
= note: required by `<flate2::read::DecoderReader<R>>::new`
我哪里错了?
编辑:最终的工作解决方案:
fn gunzip(r: &mut Response) -> String {
let mut buffer = Vec::new();
let _ = r.read_to_end(&mut buffer).unwrap();
let mut d = GzDecoder::new(buffer.as_slice()).unwrap();
let mut s = String::new();
d.read_to_string(&mut s).unwrap();
s
}
【问题讨论】:
-
(回应已删除的评论...)是的,我做到了[尝试
&zs]。结果trait '&&mut [u8]: std::io::Read' not satisfied。 -
您可以尝试添加第二个 & 吗? (这听起来很愚蠢,但它适用于 playground )
-
GzDecoder::new(&&zs).unwrap()=>trait '&&&mut [u8]: std::io::Read' not satisfied. -
这很有趣,因为它在操场上确实有效。我还要注意
[]是一个长度为 0 的数组,不允许增长。这意味着读入它最终将什么也读不到。如果您想阅读所有内容,请使用Vec试试运气,例如通过read_to_end -
您应该能够可变地借用
r并将其传递给GzDecoder,因为它接受实现Read的类型,而客户端Response会这样做。