如何在不需要分配新变量的情况下为链表实现前缀? [英] How to implement prepend for a linked list without needing to assign to a new variable?

查看:85
本文介绍了如何在不需要分配新变量的情况下为链表实现前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某事告诉我如何实现链接列表:

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

当我想使用prepend时,我需要执行以下操作:

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

list = list.prepend(1);

但是,我想创建一个不需要每次prepend返回时都创建新变量的函数.我只想使用prepend更改list变量本身:

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

错误是:

error[E0507]: cannot move out of borrowed content

推荐答案

List::prepend 必须移动self,因为这实际上是正在发生的事情.列表的新头是新对象,旧头被移到堆上,使旧变量无效.

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.

my_prepend内部,您可以对self进行可变引用,但随后移动其值,以使self引用无效.即使只是暂时无效,这也是"cannot move out of borrowed content"消息所抱怨的.

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.

解决此问题的一种方法是将self移到变量中,同时 Nil替换它,以使self引用永远不会无效.您可以使用mem::replace:

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

这篇关于如何在不需要分配新变量的情况下为链表实现前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆