too-many-lists/ok-stack/iter #796
Replies: 9 comments 12 replies
-
self.next = node.next.as_ref().take().map(| rde| &**rde); |
Beta Was this translation helpful? Give feedback.
-
Rust从入门到放弃,看了这一章,感觉像前面没学一样😢😢😢 |
Beta Was this translation helpful? Give feedback.
-
前面都学废了😮💨 |
Beta Was this translation helpful? Give feedback.
-
impl<T> List<T> {
// 此处iter的构造函数满足编译器消除规则2:"若存在多个输入生命周期,且其中一个是 &self 或 &mut self,则 &self 的生命周期被赋给所有的输出生命周期"
// 这个签名可以不写显示生命周期,优化成 `pub fn iter(&self) -> Iter<T>`
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
Iter { next: self.head.as_deref() }
}
} |
Beta Was this translation helpful? Give feedback.
-
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let old_next = self.next;
match old_next {
None => None,
Some(old_node) => {
let next_next: &Link<T> = &old_node.next;
let new_next = match next_next {
None => None,
Some(boxed_node) => {
let new_node = &**boxed_node;
Some(new_node)
}
};
self.next = new_next;
let elem = &old_node.elem;
Some(elem)
}
}
}
} 把上述代码使用match实现,可以发现代码量变得很多,个人感觉match这样或许可以方便理解。 |
Beta Was this translation helpful? Give feedback.
-
如果 pub struct Iter<T> {
next: &'a Link<T>, // same as &'a Option<Box<Node<T>>>
} 这里是完整版: pub struct Iter<'a, T> {
next: &'a Link<T>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
match self.next {
None => None,
Some(node) => {
self.next = &node.next;
Some(&node.elem)
}
}
}
}
impl<'a, T> IntoIterator for &'a LinkList<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
Iter { next: &self.head }
}
}
impl<T> LinkList<T> {
//snap
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
self.into_iter()
}
} |
Beta Was this translation helpful? Give feedback.
-
对实现了 Iterator trait 的类型,rust 会自动实现 IntoIterator trait。不用再套一层元组结构体吧。 impl<T> Iterator for List<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.pop()
}
} |
Beta Was this translation helpful? Give feedback.
-
"事实上,还可以使用另一种方式来实现:" |
Beta Was this translation helpful? Give feedback.
-
too-many-lists/ok-stack/iter
https://course.rs/too-many-lists/ok-stack/iter.html
Beta Was this translation helpful? Give feedback.
All reactions