Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
little rust starter hint series: lifetimes made easy
#[derive(Debug)]
pub struct List {
head: Link,
}
#[derive(Debug)]
pub struct Node {
next: Link,
data: i32,
}
pub type Link = Option<Box<Node>>;
impl List {}
impl Node {}
pub struct Iter<'a> {
next: Option<&'a Node>,
}
impl List {
pub fn iter(&self) -> Iter {
Iter {
next: self.head.as_ref().map(|node| &**node),
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a i32;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_ref().map(|node| &**node);
&node.data
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn list() {
let last_item = Node {
next: Link::None,
data: 2,
};
let first_item = Node {
next: Some(Box::new(last_item)),
data: 1,
};
let mut list = List {
head: Some(Box::new(first_item)),
};
println!("{:?}", list);
for x in list.iter() {
println!("{}", x);
}
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), None);
}
#[test]
fn loop_over_vec() {
let v = vec![1, 2, 3, 4, 5];
for x in v.iter() {
println!("{}", x);
}
println!("{}", v.len());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment