阅读 Rust 书中关于 智能指针和内部可变性 部分后,我尝试作为个人练习编写一个函数,用于遍历智能指针的链表并返回该链表中的“最后”元素。
这段代码导致以下错误:
我能够通过使用“匹配守卫”并在
#[derive(Debug, PartialEq)]
enum List {
Cons(Rc<RefCell<i32>>, Rc<List>),
Nil,
}
use crate::List::{Cons, Nil};
fn get_last(list: &List) -> &List {
match list {
Nil | Cons(_, Nil) => list,
Cons(_, next_list) => get_last(next_list),
}
}
这段代码导致以下错误:
| Nil | Cons(_, Nil) => list,
| ^^^ expected struct `std::rc::Rc`, found enum `List
我能够通过使用“匹配守卫”并在
Cons(_, x)
模式上显式解引用来使其正常工作:fn get_last(list: &List) -> &List {
match list {
Nil => list,
Cons(_, next_list) if **next_list == Nil => list,
Cons(_, next_list) => get_last(next_list),
}
}
考虑到我对隐式解引用和Rc
的Deref
特质实现所了解的内容,我本来希望我的第一次尝试能够成功。为什么在这个例子中我必须显式地解引用?