How to implement prepend for a linked list without needing to assign to a new variable?

后端 未结 1 497
囚心锁ツ
囚心锁ツ 2021-01-22 02:46

Something told me how to implement a linked list:

enum List {
    Cons(u32, Box),
    Nil,
}

impl List {
    fn prepend(self, elem: u32) -> List          


        
1条回答
  •  一整个雨季
    2021-01-22 03:27

    List::prepend must move self because that is literally what is happening. The new head of the list is a new object and the old head is moved onto the heap, making the old variable invalid.

    Inside my_prepend you have a mutable reference to self, but then you move its value so that the self reference becomes invalid. Even though it's only invalid temporarily, this is what the message "cannot move out of borrowed content" is complaining about.

    One way to get around this is to move self out into a variable and simultaneously replace it with Nil, so that the self reference is never invalid. You can do that with mem::replace:

    use std::mem;
    
    fn my_prepend(&mut self, elem: u32) {
        // Move the value of self into head, and leave self as Nil so it isn't invalid
        let head = mem::replace(self, List::Nil);
        // Reassign to self with the prepended value
        *self = head.prepend(elem);
    }
    

    0 讨论(0)
提交回复
热议问题