cannot move out of a mutable reference Rust. error[E0507] from a leetcode problme(LinkedList for sure)

aydmsdu9  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(108)

我正在学习Rust,并试图用leetcode问题来练习它。以下是我为LC19. Remove Nth Node From End of List编写的代码。

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
// 
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }

    pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
        if head.is_none() {
            return head;
        }
        
        let mut dummy = Box::new(ListNode::new(0));
        dummy.next = head;

        let mut cur = dummy.clone();
        let mut prev = dummy.as_mut();
        
        for _ in 0..n {
            cur = cur.next.unwrap();
        }
        
        loop {
            match &cur.next {
                None => break,
                Some(_) => {
                    cur = cur.next.unwrap();
                    prev = prev
                            .next
                            .as_mut()
                            .unwrap();
                }
            }
        }

        // ---- Here is where the problem happened ----
        prev.next = prev
                        .next
                        .as_mut()
                        .unwrap()
                        .next;

        return dummy.next;

    }

编译器会报告以下问题:

error[E0507]: cannot move out of a mutable reference
  --> src/leetcode/lc00019/solution.rs:39:15
   |
39 |         prev.next = prev.next.as_mut().unwrap().next;
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `Option<Box<list_node::ListNode>>`, which does not implement the `Copy` trait

下面的代码可以工作,这让我很困惑,但我不明白为什么

prev.next = prev
                        .next
                        .as_mut()
                        .unwrap() // -> &mut Box<ListNode>
                        .next     // -> Option<Box<ListNode>>
                        .take();  // -> Option<Box<ListNode>>

nexttake()都给出了相同的类型Option<Box<ListNode>>,那么为什么删除take()编程失败?
任何RustMaven都可以解释吗?

xdnvmnnf

xdnvmnnf1#

快速浏览一下take在文档中的作用,我们可以了解更多的情况:Takes the value out of the option, leaving a None in its place..
prev.next = prev.next.as_mut().unwrap().next;尝试将Option本身移出prev时,根本不留下任何值,take将使用该可变引用仅移动Option内部的内容,将Option::SomeOption::None交换,但Option本身保留。

相关问题