SHARE
TWEET

Untitled

a guest Feb 17th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct A {
  2.     v: Vec<String>,
  3. }
  4. struct AIter<'a> {
  5.     a: &'a A,
  6.     now: usize,
  7. }
  8. struct AIter2 {
  9.     now: usize,
  10. }
  11. impl A {
  12.     fn new(v: Vec<&str>) -> A {
  13.         A {
  14.             v: v.iter().map(|s| s.to_string()).collect(),
  15.         }
  16.     }
  17.  
  18.     fn iter(&self) -> AIter {
  19.         AIter { a: &self, now: 0 }
  20.     }
  21.     fn iter2(&self) -> AIter2 {
  22.         AIter2 { now: 0 }
  23.     }
  24. }
  25.  
  26. impl<'a> Iterator for AIter<'a> {
  27.     type Item = &'a str;
  28.     fn next(&mut self) -> Option<&'a str> {
  29.         self.now += 1;
  30.         if self.now - 1 < self.a.v.len() {
  31.             Some(&self.a.v[self.now - 1])
  32.         } else {
  33.             None
  34.         }
  35.     }
  36. }
  37. impl Iterator for AIter2 {
  38.     type Item = usize;
  39.     fn next(&mut self) -> Option<usize> {
  40.         self.now += 1;
  41.         Some(self.now - 1)
  42.     }
  43. }
  44.  
  45. fn take5<T>(iter: impl Iterator<Item = T>) -> Vec<T> {
  46.     iter.take(5).collect()
  47. }
  48.  
  49. fn main() {
  50.     let a = A::new(vec!["a", "b", "c", "d", "e", "f", "g"]);
  51.     assert_eq!(vec!["a", "b", "c", "d", "e"], take5(a.iter()));
  52.     assert_eq!(vec![0, 1, 2, 3, 4], take5(a.iter2()));
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top