我搞不懂为什么要编译这段代码:
use std::io::{Read, BufRead};
trait ReadString {
fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String>;
}
impl<R> ReadString for R
where
R: BufRead,
{
fn read_null_terminated_string(&mut self, max_size: u64) -> std::io::Result<String> {
let mut buf = Vec::new();
self.take(max_size).read_until(0, &mut buf)?;
Ok(String::from_utf8_lossy(&buf).to_string())
}
}
据我所知,BufRead
不是Copy
,BufRead::take()
是:
fn take(self, limit: u64) -> Take<Self>
where
Self: Sized,
{
Take { inner: self, limit }
}
那么.take()
肯定应该移动self
,这是不允许的,因为我只有&mut self
?我甚至试着用我自己的类似BufRead
的特征,但我确实收到了这个错误:
cannot move out of `*self` which is behind a mutable reference
move occurs because `*self` has type `R`, which does not implement the `Copy` trait
那么为什么我不能得到BufRead
的错误呢?