Skip to content

Instantly share code, notes, and snippets.

@matematikaadit
Last active January 7, 2017 10:41
Show Gist options
  • Save matematikaadit/50549cbd5a6c567abd131653f6167a3e to your computer and use it in GitHub Desktop.
Save matematikaadit/50549cbd5a6c567abd131653f6167a3e to your computer and use it in GitHub Desktop.
fn main() {
let mut data = Data::new(10);
println!("{:?}", data);
for n in data.iter() {
// you can't use data here
// this line fail:
// println!("{:?}", data);
println!("{}", n);
}
println!("{:?}", data);
}
#[derive(Debug)]
struct Data {
num: u8,
finished: bool,
}
struct Iter<'a>(&'a mut Data);
impl Data {
fn new(n: u8) -> Self {
Data { num: n, finished: false }
}
fn iter(&mut self) -> Iter {
Iter(self)
}
}
impl<'a> Iterator for Iter<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
if self.0.num < 1 {
self.0.finished = true;
None
} else {
let num = self.0.num;
self.0.num -= 1;
Some(num)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment