Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub struct FamilyIterator<'a> {
- offset: usize,
- family: &'a Family,
- }
- impl<'a> Iterator for FamilyIterator<'a> {
- type Item = &'a Person;
- fn next(&mut self) -> Option<&'a Person> {
- let result = match self.offset {
- 0 => &self.family.a,
- 1 => &self.family.b,
- 2 => &self.family.c,
- _ => return None,
- };
- self.offset += 1;
- Some(&result)
- }
- }
- impl<'a> IntoIterator for &'a Family {
- type Item = &'a Person;
- type IntoIter = FamilyIterator<'a>;
- fn into_iter(self) -> Self::IntoIter {
- FamilyIterator {
- offset: 0,
- family: self,
- }
- }
- }
- #[derive(Debug)]
- pub struct Person {
- age: usize,
- }
- #[derive(Debug)]
- pub struct Family {
- a: Person,
- b: Person,
- c: Person,
- }
- fn main() {
- let family = Family {
- a: Person { age: 1 },
- b: Person { age: 2 },
- c: Person { age: 3 },
- };
- println!("Current family: {:?}", family);
- /*
- for person in &family {
- println!("Person's age: {:?}", person.age);
- person.age += 1
- }*/
- println!("Updated family: {:?}", family);
- }
Add Comment
Please, Sign In to add comment