问题
I'm trying to implement deserializer for a BERT data which comes from an another program via sockets. For the following code:
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)
}
}
The Rust compiler generates an error, when I'm trying to read a string from a passed data:
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
How can I fix this even if my Deserializer<R>
struct has had Clone/Copy
traits?
回答1:
The take
method takes self
:
fn take(self, limit: u64) -> Take<Self> where Self: Sized
so you cannot use it on anything borrowed.
Use the by_ref
method. Replace the error line with this:
{
let reference = self.reader.by_ref();
reference.take(len as u64).read_to_string(&mut string_buffer);
}
来源:https://stackoverflow.com/questions/39377246/cannot-move-out-of-borrowed-content-for-a-struct