无法移出结构的借用内容 [英] Cannot move out of borrowed content for a struct

查看:112
本文介绍了无法移出结构的借用内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为通过套接字从另一个程序来的BERT数据实现反序列化。对于以下代码:

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

Rust编译器当我尝试从传递的数据中读取字符串时,会生成错误:

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

即使我的 Deserializer< R> 结构具有 Clone / Copy ,该如何解决?

How can I fix this even if my Deserializer<R> struct has had Clone/Copy traits?

推荐答案

take 方法需要自我

fn take(自我,限制:u64)->采取< Self>自我:尺寸 c

所以您不能在借来的东西上使用它。

so you cannot use it on anything borrowed.

使用 by_ref 方法。用以下代码替换错误行:

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

这篇关于无法移出结构的借用内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆