如何解决锈盒和移动
我有以下代码:
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)
}
}
}
}
但是当我将 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
似乎移动发生在第 35 行。我的问题是:
- 在我改变之前是否发生了移动?
- 为什么在我改变之前它有效?
事实上,我正在阅读"Learn Rust by writing Entirely Too Many Linked Lists"。我注意到在 this commit 中,提交者将一些内容更改为更新到 rust 2018。这些更改似乎与我的问题有关。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。