0

我正在尝试为通过套接字来自另一个程序的 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

4

1 回答 1

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);
}
于 2016-09-07T19:20:26.837 回答