不能搬出借来的内容不能搬出借来的内容(Cannot move out of borrowed con

2019-05-10 10:27发布

我不明白的错误cannot move out of borrowed content 。 我收到了很多次,我一直解决了它,但我永远无法理解为什么。

例如:

for line in self.xslg_file.iter() {
    self.buffer.clear();

    for current_char in line.into_bytes().iter() {
        self.buffer.push(*current_char as char);
    }

    println!("{}", line);
}

产生错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:31:33
   |
31 |             for current_char in line.into_bytes().iter() {
   |                                 ^^^^ cannot move out of borrowed content

我解决它通过克隆line

for current_char in line.clone().into_bytes().iter() {

我甚至阅读其他职位等之后,不理解的错误:

  • 无法从与MUT自借入文件(错误消息:无法搬出借来的内容)
  • 在拉斯特树更改节点

这是什么样的错误的由来?

Answer 1:

让我们来看看签名into_bytes

fn into_bytes(self) -> Vec<u8>

这需要self ,而不是自(基准&self )。 这意味着, self会被消耗掉 ,并在呼叫后无法使用。 在其位,你会得到一个Vec<u8> 前缀into_是表示以这样的方法的一种常见方式。

我不知道到底是什么你iter()方法返回,但我的猜测是,它在是一个迭代器&String ,也就是说,它返回引用一个String ,但不给你他们的所有权。 这意味着你不能调用消耗值的方法

正如您看到的,一个解决方案是使用clone 。 这将创建你自己一个重复的对象,并可以调用into_bytes上。 正如其他评论者提到,您也可以使用as_bytes这需要&self ,所以它会在借来的价值的工作。 哪一个你应该使用取决于你的最终目标是为你使用指针做什么。

从宏观角度来看,这一切都与所有权的概念做。 某些操作取决于拥有的项目,以及其他操作可以逃脱借款对象(或许是性情不定地)。 参考( &foo )不授予所有权,它只是一个借位。

为什么有趣用self的,而不是&self在一个函数的参数呢?

过户是在一般一个有用的概念 - 当我的东西做了,其他人可能有它。 生锈,这是一种方式更有效率。 我能避免分配一个副本,给你一个副本,然后扔掉我的副本。 所有权也是最宽松的状态; 如果我自己的目标,我可以,我想用它做。


下面是我创建了测试代码:

struct IteratorOfStringReference<'a>(&'a String);

impl<'a> Iterator for IteratorOfStringReference<'a> {
    type Item = &'a String;

    fn next(&mut self) -> Option<Self::Item> {
        None
    }
}

struct FileLikeThing {
    string: String,
}

impl FileLikeThing {
    fn iter(&self) -> IteratorOfStringReference {
        IteratorOfStringReference(&self.string)
    }
}

struct Dummy {
    xslg_file: FileLikeThing,
    buffer: String,
}

impl Dummy {
    fn dummy(&mut self) {
        for line in self.xslg_file.iter() {
            self.buffer.clear();

            for current_char in line.into_bytes().iter() {
                self.buffer.push(*current_char as char);
            }

            println!("{}", line);
        }
    }
}

fn main() {}


文章来源: Cannot move out of borrowed content
标签: rust