From 2bc9c68293ef6f6cd12ccfb5bcfa1959e313baf7 Mon Sep 17 00:00:00 2001 From: jb-alvarado Date: Thu, 17 Feb 2022 17:25:52 +0100 Subject: [PATCH] add iter example --- examples/custom_iter.rs | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 examples/custom_iter.rs diff --git a/examples/custom_iter.rs b/examples/custom_iter.rs new file mode 100644 index 00000000..cc804640 --- /dev/null +++ b/examples/custom_iter.rs @@ -0,0 +1,57 @@ +use std::{ + thread::sleep, + time::Duration, +}; + +struct List { + arr: Vec, + msg: String, + i: usize, +} + +impl List { + fn new() -> Self { + Self { + arr: (0..10).collect(), + msg: "fist init".to_string(), + i: 0, + } + } + + fn fill(&mut self, val: String) { + println!("{val}"); + self.msg = "new fill".to_string(); + } +} + +impl Iterator for List { + type Item = u8; + + fn next(&mut self) -> Option { + if self.i == 0 { + println!("{}", self.msg); + } + if self.i < self.arr.len() { + let current = self.arr[self.i]; + self.i += 1; + + Some(current) + } else { + self.i = 1; + let current = self.arr[0]; + self.fill("pass to function".to_string()); + println!("{}", self.msg); + + Some(current) + } + } +} + +fn main() { + let list = List::new(); + + for i in list { + println!("{i}"); + sleep(Duration::from_millis(300)); + } +}