Last active
January 7, 2017 10:41
-
-
Save matematikaadit/50549cbd5a6c567abd131653f6167a3e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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