Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Last active December 25, 2018 11:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyinyithann/8a079c075acc998d242944a7bc383ec8 to your computer and use it in GitHub Desktop.
Save nyinyithann/8a079c075acc998d242944a7bc383ec8 to your computer and use it in GitHub Desktop.
Implement Iterator trait to Counter
/* Counter example can be seen at https://doc.rust-lang.org/std/iter/index.html#implementing-iterator
I just wanna try out implementing Iterator trait on tuple like struct.
Due to the IntoIterator blanket implementation in standard library - "impl<I: Iterator> IntoIterator for I" ,
all Iterator can be treated like IntoIterator. That's why we can call c.into_iter() in the code.
*/
use std::iter::*;
fn main() {
let mut z = 0u32;
let ref mut c = Counter(&mut z);
let iter = c.into_iter();
while let Some(v) = iter.next() {
if v > 100 {
break;
}
println!("{}", v);
}
println!("{:?}", c);
c.reset();
println!("{:?}", c);
}
#[derive(Debug)]
struct Counter<'a>(&'a mut u32);
impl<'a> Counter<'a> {
fn reset(&mut self) {
*self.0 = 0
}
}
impl<'a> Iterator for Counter<'a> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
*self.0 = *self.0 + 1;
Some(*self.0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment