如何在Rust中将元素插入链表的前面?

huangapple go评论56阅读模式
英文:

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&lt;Box&lt;ListNode&gt;&gt;
}
impl ListNode {
    fn new(val: i32) -&gt; Self {
        println!(&quot;Call new {}&quot;, val);
        return ListNode {
            val: val,
            next: None
        };
    }

    fn push_front(self, &amp;mut new_head: &amp;mut ListNode) -&gt; 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(&amp;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) -&gt; 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!(&quot;{node2:?}&quot;);
}

huangapple
  • 本文由 发表于 2023年7月14日 00:38:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定