0

I am practicing Rust by implementing a listed list, when I write the function insert_after, I got a compiler error, but when I use take method of Option, it disappears, I want to know why because i think that node.next are all option, it should be assignable.

Thanks for any help ~~

pub struct  LinkListNode<T> {
    body: T,
    next: LinkdListNodeLink<T>
}

type LinkdListNodeLink<T> = Option<Box<LinkListNode<T>>>;

pub struct LinkdList<T> {
    head: LinkdListNodeLink<T>
}

impl <T: std::fmt::Debug> LinkdList<T> {
    pub fn new() -> Self {
        LinkdList { head: None }
    }
    pub fn insert_after(&mut self, value: T, index: u32) -> Result<(), u32> {
        match self.head.as_mut() {
            None => {
                self.head = Some(Box::new( LinkListNode { body: value, next: None }));
                return Ok(());
            }
            Some(mut node) => {
                for i in 0..index {
                   match node.next.as_mut() {
                    Some(next_node) => {
                        node = next_node;
                    }
                    None => {
                        return Err(i);
                    }
                   }
                }
                let mut new_node = Box::new(LinkListNode { body: value, next: None });
                new_node.next = node.next; // error disappears when i use node.next.take
                node.next = Some(new_node);

                return Ok(());
            }
        }

    }
}

enter image description here

steven-lie
  • 75
  • 2
  • 7
  • 1
    Please do not post errors as images. And please post the full error from `cargo check`, not your IDE. – Chayim Friedman Jun 22 '23 at 19:11
  • 3
    Practicing Rust by implementing linked lists is not a great idea. Anyway, mandatory reference: https://rust-unofficial.github.io/too-many-lists/. – Chayim Friedman Jun 22 '23 at 19:12
  • Does this answer your question? [Temporarily move out of borrowed content](https://stackoverflow.com/questions/29570781/temporarily-move-out-of-borrowed-content) – Chayim Friedman Jun 22 '23 at 19:15
  • rust installation should come with a BIG RED LINE in the terminal saying DON'T DO LINKED LIST – Stargateur Jun 22 '23 at 19:46

1 Answers1

1

When you write new_node.next = node.next, what you are trying to do is "transfer" ownership of node's next to new_node's next. but node is just a mutable reference. It doesn't "own" data and therefore cannot transfer ownership.

Below is the definition of Option::take from rustc 1.70.

    pub const fn take(&mut self) -> Option<T> {
        // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
        mem::replace(self, None)
    }


If you notice, it only needs a &mut self, and it puts None in the place and return whatever was there.

kumarmo2
  • 1,381
  • 1
  • 20
  • 35