Created
January 15, 2023 11:56
-
-
Save cambiata/e6657fdb47427642514b552fe785a559 to your computer and use it in GitHub Desktop.
Rust iterator implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug)] | |
pub struct TestItem { | |
val: usize, | |
} | |
#[derive(Debug)] | |
pub struct TestItems<'a> { | |
items: &'a Vec<&'a TestItem>, | |
idx: usize, | |
pos: usize, | |
} | |
impl<'a> TestItems<'a> { | |
fn new(items: &'a Vec<&'a TestItem>) -> Self { | |
Self { | |
items, | |
idx: 0, | |
pos: 0, | |
} | |
} | |
} | |
impl<'a> Iterator for TestItems<'a> { | |
type Item = (usize, &'a TestItem); | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.idx < self.items.len() { | |
let item = self.items[self.idx]; | |
let curr_pos = self.pos; | |
self.idx += 1; | |
self.pos += item.val; | |
return Some((curr_pos, item)); | |
} | |
None | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
#[allow(unused)] | |
use crate::{TestItem, TestItems}; | |
#[test] | |
fn test3() { | |
let vec = vec![&TestItem { val: 10 }, &TestItem { val: 20 }]; | |
let test = TestItems::new(&vec); | |
println!("test:{:?}", test); | |
for item in test { | |
println!("- item:{:?}", item); | |
} | |
println!("test:{:?}", vec); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment