【发布时间】:2020-11-01 04:41:16
【问题描述】:
阅读 Rust 书中Smart Pointers and Interior mutability 上的部分后,作为个人练习,我尝试编写一个函数,该函数将遍历智能指针的链表并返回列表中的“最后一个”元素:
#[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),
}
}
鉴于我对隐式取消引用和Deref 特征实现Rc 的了解,我预计我的第一次尝试会奏效。为什么我必须在此示例中显式取消引用?
【问题讨论】:
标签: rust dereference coercion