gpt4 book ai didi

rust - 错误 : cannot move out of borrowed content for self field

转载 作者:行者123 更新时间:2023-11-29 08:03:07 25 4
gpt4 key购买 nike

这是我的代码:

struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}

impl<T> Node<T> {
fn new(data : T) -> Node<T> {
Node { data: data, next: None }
}
fn new_with_next(data: T, next: Option<Box<Node<T>>>) -> Node<T> {
Node { data: data, next: next }
}
}


struct LinkedList<T> {
head: Box<Node<T>>,
size: u8,
}

impl<T> LinkedList<T> {
fn new(data: T) -> LinkedList<T> {
let new_node = Node::new(data);
let head = Box::new(new_node);
LinkedList { head: head, size: 1 }
}
fn insert(&mut self, data: T) {
let mut next = Some(self.head); // <-- error here
let new_node = Node::new_with_next(data, next);
self.head = Box::new(new_node);
self.size += 1;
}
}

我收到这个错误:

src\linked_list.rs:28:29: 28:33 error: cannot move out of borrowed content [E0507]
src\linked_list.rs:28 let next = Some(self.head);
^~~~

我不明白这个错误,也不明白如何修复它。我尝试将对 self.head 的引用提供给 Some,但是我正在以这种方式更改 Some 中的数据类型。

最佳答案

问题是你通过引用获取self,因此你不能移出它的head(它会变得无效),let mut next = Some (self.head); 会做。

std::mem::replace这是一个很好的功能:

fn insert(&mut self, data: T) {
let mut next = std::mem::replace(&mut self.head, Box::new(Node::new(data)));
self.head.next = Some(next);
self.size += 1;
}

它允许您用新节点替换 head 并同时获取旧节点,Rust 对此很高兴,因为 head 现在一直有效.

关于rust - 错误 : cannot move out of borrowed content for self field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com