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

别说谁变了你拦得住时间么 提交于 2019-12-02 06:25:01

问题


Something told me how to implement a linked list:

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

impl List {
    fn prepend(self, elem: u32) -> List {
        Cons(elem, Box::new(self))
    }
}

When I want to use prepend, I need to do the following:

list = list.prepend(1);

However, I want to create a function that does not need to create a new variable every time prepend returns. I just want to change the list variable itself using prepend:

list.prepend(1);

Here is one implementation that I come up with, but it's not right:

fn my_prepend(&mut self, elem: u32) {
    *self = Cons(elem, Box::new(*self));
}

The error is:

error[E0507]: cannot move out of borrowed content

回答1:


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);
}


来源:https://stackoverflow.com/questions/51836940/how-to-implement-prepend-for-a-linked-list-without-needing-to-assign-to-a-new-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!