无法移出结构的借用内容

时间:2016-09-07 18:54:47

标签: rust deserialization borrowing

我正在尝试为来自另一个程序的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特征,我该如何解决这个问题?

1 个答案:

答案 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);
}