Skip to content

7.迭代器

实现 Iterator trait

rust
struct MyType {
  items: Vec<String>
}

struct MyTypeIterator<'a> {
  index: usize,
  items: &'a Vec<String>
}

impl<'a> Iterator for MyTypeIterator<'a> {
  type Item = &'a String;

  fn next(&mut self) -> Option<Self::Item> {
    if self.index < self.items.len() {
      let item = Some(&self.items[self.index]);
      self.index += 1;
      item
    } else {
      None
    }
  }
}

fn main() {
  let myType = MyType {
    items: vec!["1", "2", "3"].iter().map(|e| e.to_string()).collect()
  };

  let myTypeIter = MyTypeIterator {
    index: 0,
    items: &myType.items
  };

  for item in myTypeIter {
    println!("{}", item);
  }
}
struct MyType {
  items: Vec<String>
}

struct MyTypeIterator<'a> {
  index: usize,
  items: &'a Vec<String>
}

impl<'a> Iterator for MyTypeIterator<'a> {
  type Item = &'a String;

  fn next(&mut self) -> Option<Self::Item> {
    if self.index < self.items.len() {
      let item = Some(&self.items[self.index]);
      self.index += 1;
      item
    } else {
      None
    }
  }
}

fn main() {
  let myType = MyType {
    items: vec!["1", "2", "3"].iter().map(|e| e.to_string()).collect()
  };

  let myTypeIter = MyTypeIterator {
    index: 0,
    items: &myType.items
  };

  for item in myTypeIter {
    println!("{}", item);
  }
}