-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterators.rs
46 lines (39 loc) · 880 Bytes
/
iterators.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct Backpack {
things: Vec<String>,
}
impl Backpack {
fn iter(&self) -> BackpackIterator {
BackpackIterator {
index: 0,
stuff: self,
}
}
}
pub struct BackpackIterator<'a> {
index: usize,
stuff: &'a Backpack,
}
impl Iterator for BackpackIterator<'_> {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.stuff.things.len() {
let thing = Some(self.stuff.things[self.index].clone());
self.index += 1;
return thing;
}
None
}
}
pub fn main() {
let s = Backpack {
things: vec![
"laptop".to_string(),
"headphones".to_string(),
"hoodie".to_string(),
"drum sticks".to_string(),
],
};
for t in s.iter() {
println!("{}", t);
}
}