Last active
December 25, 2018 11:17
-
-
Save nyinyithann/8a079c075acc998d242944a7bc383ec8 to your computer and use it in GitHub Desktop.
Implement Iterator trait to Counter
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
/* 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