【发布时间】:2021-11-25 09:28:56
【问题描述】:
我正在 rust 中实现一个双链表。我创建了一个运行良好的迭代器。
#[derive(Clone, Debug)]
pub struct LLCursor<T: Copy> {
pub cur: Option<Rc<RefCell<Node<T>>>>,
}
impl<T> IntoIterator for List<T>
where
T: Clone + Copy,
{
type Item = Rc<RefCell<Node<T>>>;
type IntoIter = LLCursor<T>;
fn into_iter(self) -> Self::IntoIter {
LLCursor {
cur: self.head.clone(),
}
}
}
impl<T> Iterator for LLCursor<T>
where
T: Copy,
{
type Item = Rc<RefCell<Node<T>>>;
fn next(&mut self) -> Option<Rc<RefCell<Node<T>>>> {
match self.cur.clone() {
Some(node) => {
self.cur = node.borrow().next.clone();
Some(node)
}
None => None,
}
}
}
我想创建一个函数,可以在迭代时访问链表的节点内容。像这样的:
pub fn print(self)
where
List<T>: IntoIterator,
<List<T> as IntoIterator>::Item: std::fmt::Debug,
{
for i in self {
println!("{:?}", Some(i.borrow().clone().item));
}
}
错误:
error[E0599]: no method named `borrow` found for associated type `<List<T> as IntoIterator>::Item` in the current scope
--> src/list.rs:90:51
|
90 | println!("{:?}", i.borrow().clone().item);
| ^^^^^^ method not found in `<List<T> as IntoIterator>::Item`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use std::borrow::Borrow;`
我知道在这种情况下i 是<List<T> as IntoIterator>::Item 类型。我是 rust 新手,所以我看不出迭代器以这种方式返回关联类型有什么用处。我希望i 的类型为Option<Rc<RefCell<Node<T>>>>。有没有办法可以将其从关联类型中提取出来,以便能够访问每个单独节点的元素?
【问题讨论】:
标签: rust iterator associated-types