英文:
How to push front in linked list Rust?
问题
我在Rust中尝试实现链表。我的代码:
#[derive(Eq, PartialEq, Clone, Debug)]
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(val: i32) -> Self {
println!("Call new {}", val);
return ListNode {
val: val,
next: None,
};
}
fn push_front(&mut self, new_head: &mut ListNode) {
let old_next = std::mem::replace(&mut new_head.next, None);
self.next = Some(Box::new(std::mem::replace(new_head, ListNode::new(0))));
new_head.next = old_next;
}
}
fn main() {
let mut node1 = ListNode::new(1);
let mut node2 = ListNode::new(2);
node2.push_front(&mut node1);
}
我在以下代码中有一个错误:
error[E0507]: cannot move out of a mutable reference: fn push_front(self, &mut new_head: &mut ListNode)
如何修复这个错误?我认为Copy trait的实现不是一个好主意。
希望这能帮助你解决问题。如果你有任何其他问题,请随时提出。
英文:
I am trying to implement linked list in Rust. My code:
#[derive(Eq, PartialEq, Clone, Debug)]
struct ListNode {
val: i32,
next: Option<Box<ListNode>>
}
impl ListNode {
fn new(val: i32) -> Self {
println!("Call new {}", val);
return ListNode {
val: val,
next: None
};
}
fn push_front(self, &mut new_head: &mut ListNode) -> ListNode {
new_head.next = Some(Box::new(self));
return new_head;
}
}
fn main() {
let mut node1 = ListNode::new(1);
let mut node2 = ListNode::new(2);
node2 = node1.push_front(&mut node2);
}
I have an error in
> error[E0507]: cannot move out of a mutable reference: fn push_front(self, &mut new_head: &mut ListNode) -> ListNode {
How can I fix the error? I think that Copytrait implementation is not a good idea
答案1
得分: 4
你直接从 push_front
返回 ListNode
,这意味着返回值将被移出。但是当你只有一个引用时,你不能移动数据。
如果你确定想让调用者拥有所有权,你可以允许将 new_head
参数也移动到函数中。
impl ListNode {
// ...
fn push_front(self, mut new_head: ListNode) -> ListNode {
new_head.next = Some(Box::new(self));
new_head
}
}
fn main() {
let node1 = ListNode::new(1);
let mut node2 = ListNode::new(2);
node2 = node1.push_front(node2);
println!("{node2:?}");
}
英文:
You're directly returning ListNode
from push_front
, which means that the return value will be moved out. But you cannot move the data when you only have a reference.
If you are sure that you want the caller to take ownership, you can allow the new_head
argument to be moved into the function too.
impl ListNode {
// ...
fn push_front(self, mut new_head: ListNode) -> ListNode {
new_head.next = Some(Box::new(self));
new_head
}
}
fn main() {
let node1 = ListNode::new(1);
let mut node2 = ListNode::new(2);
node2 = node1.push_front(node2);
println!("{node2:?}");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论