Skip to content

Instantly share code, notes, and snippets.

@cambiata
Created January 15, 2023 11:56
Show Gist options
  • Save cambiata/e6657fdb47427642514b552fe785a559 to your computer and use it in GitHub Desktop.
Save cambiata/e6657fdb47427642514b552fe785a559 to your computer and use it in GitHub Desktop.
Rust iterator implementation
#[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