我正在尝试为来自另一个程序的BERT数据实现反序列化器。对于以下代码:
use std::io::{self, Read};
#[derive(Clone, Copy)]
pub struct Deserializer<R: Read> {
reader: R,
header: Option<u8>,
}
impl<R: Read> Read for Deserializer<R> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.reader.read(buf)
}
}
impl<R: Read> Deserializer<R> {
/// Creates the BERT parser from an `std::io::Read`.
#[inline]
pub fn new(reader: R) -> Deserializer<R> {
Deserializer {
reader: reader,
header: None,
}
}
#[inline]
pub fn read_string(&mut self, len: usize) -> io::Result<String> {
let mut string_buffer = String::with_capacity(len);
self.reader.take(len as u64).read_to_string(&mut string_buffer);
Ok(string_buffer)
}
}
当我尝试从传递的数据中读取字符串时,Rust编译器会生成错误:
error: cannot move out of borrowed content [E0507]
self.reader.take(len as u64).read_to_string(&mut string_buffer);
^~~~
help: run `rustc --explain E0507` to see a detailed explanation
即使我的Deserializer<R>
结构具有Clone/Copy
特征,我该如何解决这个问题?
答案 0 :(得分:6)
take
方法需要self
:
fn take(self, limit: u64) -> Take<Self> where Self: Sized
所以你不能在借来的东西上使用它。
使用by_ref
方法。用以下内容替换错误行:
{
let reference = self.reader.by_ref();
reference.take(len as u64).read_to_string(&mut string_buffer);
}