【发布时间】: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