From 105f3ee65d6d52bdeddda90afde8ebfcacc416e8 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Thu, 26 Aug 2021 18:30:39 +0200 Subject: [PATCH] Iterators --- src/lib.rs | 23 +++++++++++++++++++++++ src/main.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index fe3b71b..b7e5eb8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -85,3 +85,26 @@ where } } } + +pub struct Counter5 { + count: u32 +} + +impl Counter5 { + pub fn new() -> Counter5 { + Counter5 { count: 0 } + } +} + +impl Iterator for Counter5 { + type Item = u32; + + fn next(&mut self) -> Option { + if self.count < 5 { + self.count += 1; + Some(self.count) + } else { + None + } + } +} diff --git a/src/main.rs b/src/main.rs index 3b45c88..06d122b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -157,6 +157,38 @@ fn test_closures() { println!("1st int call for value defg: {}", expensive_str_result.value("defg")); } +fn test_iterators() { + let v1 = vec!["Hello", "good", "world"]; + // implied default is .into_iter() which consumes v1 + for s in v1.iter() { + println!("element: {}", s); + } + // can still use it now + println!("v1: {:?}", &v1); + + // manual iteration + let mut v1_iter = v1.iter(); + while let Some(e) = v1_iter.next() { + println!("while loop over iter: {}", e); + } + + for l_element in v1.iter().filter(|x| x.contains('l')) { + println!("v1 element containing 'l': {}", l_element); + } + + let v2 = vec![1, 2, 3]; + let double_v2: Vec<_> = v2.iter().map(|x| x * 2).collect(); + println!("doubled v2: {:?}", double_v2); + + for i in v2.into_iter().map(|x| x * 3) { + println!("for loop triplicating v2: {}", i); + } + + for i in Counter5::new() { + println!("Counter 5 value: {}", i); + } +} + fn main() { test_strings(); test_vectors(); @@ -164,4 +196,5 @@ fn main() { test_files(); test_generics(); test_closures(); + test_iterators(); } -- 2.39.5