简体   繁体   English

锈盒和移动

[英]Rust Box and move

I have the following code:我有以下代码:

use std::{borrow::BorrowMut, mem};

struct Node {
    ele: i32,
    next: List,
}

enum List {
    Empty,
    More(Box<Node>),
}

pub struct LinkedList {
    head: List,
}

impl LinkedList {
    pub fn new() -> Self {
        LinkedList { head: List::Empty }
    }

    pub fn push(&mut self, value: i32) {
        let new_node = Box::new(Node {
            ele: value,
            next: mem::replace(self.head.borrow_mut(), List::Empty),
        });

        self.head = List::More(new_node);
    }

    pub fn pop(&mut self) -> Option<i32> {
        match mem::replace(self.head.borrow_mut(), List::Empty) {
            List::Empty => None,
            List::More(node) => { // node have type Box<Node>
                self.head = node.next;
                Some(node.ele)
            }
        }
    }
}

But when I change List::More(node) => { to List::More(ref node) => { , will produce the error:但是当我将List::More(node) => {更改为List::More(ref node) => { ,会产生错误:

error[E0507]: cannot move out of `node.next` which is behind a shared reference
  --> src/first.rs:35:29
   |
35 |                 self.head = node.next;
   |                             ^^^^^^^^^ move occurs because `node.next` has type `List`, which does not implement the `Copy` trait

It seems that the move occurs in line 35. My questions are:似乎移动发生在第 35 行。我的问题是:

  • Does a move occurred before I changed?在我改变之前发生了移动吗?
  • Why it works before I changed?为什么它在我改变之前有效?

In fact, I'm reading "Learn Rust by writing Entirely Too Many Linked Lists" .事实上,我正在阅读“通过编写完全太多的链接列表来学习 Rust” I noticed that in this commit , the committer changed something to updating to rust 2018. These changes seem to related to my question.我注意到在这个提交中,提交者将某些内容更改为更新到 rust 2018。这些更改似乎与我的问题有关。

self.head is of type List , as declared in struct List { ... } . self.headList类型,如struct List { ... }所声明的。 Therefore, an owned List must be assigned to self.head .因此,必须将拥有的List分配给self.head &List and &mut List are not owned, but references. &List&mut List不是拥有的,而是引用。 So when assigning to self.head , you must have ownership of the value you want to assign.因此,在分配给self.head ,您必须拥有要分配的值的所有权 If you change the match arm to List::More(ref node) => { , node is of type &List , which is a reference and not an owned value and therefore not assignable to self.head .如果将 match arm 更改为List::More(ref node) => {node的类型是&List ,它是一个引用而不是一个拥有的值,因此不能分配给self.head

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM