【问题标题】:How to pop a value from cons list?如何从 cons 列表中弹出一个值?
【发布时间】:2021-12-08 06:59:49
【问题描述】:

在 The Book 的第 15.1 章中,展示了 Box<> 用于递归类型(cons list)实现的示例。我试图为这个 cons 列表实现一种方法,以将最外层的值弹出列表,留下任何剩余的值或Nil,如果没有剩余。但它不起作用,我不知道如何在 self 解构后对其进行变异时返回值(所以借用?)。方法中的引用对我来说真的没有任何意义....

如果不创建一个使用列表并吐出值和新列表的函数,有没有办法做到这一点?

这是我的代码:

use crate::List::{Cons, Nil};

fn main() {
    let mut list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));

    println!("The first value is: {}.", list.pop().unwrap());
    println!("The second value is: {}.", list.pop().unwrap());
}

#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

impl List {
    // It seems to me I need to mutably borrow the list to change it
    // but the way reference types behave later confuses me
    fn pop(&mut self) -> Option<i32> {
        if let Cons(value, list) = &self {
            self = **list; // <- how to do this bit? self is borrowed...
            Some(*value)
        } else {
            None
        }
    }
}

【问题讨论】:

标签: data-structures rust borrow-checker cons


【解决方案1】:

您可以通过首先将当前列表移出self 并将其替换为Nil 来使您的方法有效。这样,你可以在旧列表上匹配,仍然可以分配给self

fn pop(&mut self) -> Option<i32> {
    let old_list = std::mem::replace(self, Nil);
    match old_list {
        Cons(value, tail) => {
            *self = *tail;
            Some(value)
        }
        Nil => None,
    }
}

(Playground)

【讨论】:

  • 太棒了,是的,行得通;还没见过replace这个函数,看起来挺方便的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多