无法移出结构的借用内容

Cannot move out of borrowed content for a struct

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

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