Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. use std::iter::IntoIterator;
  2.  
  3. struct MyStructIterator<'a, T> {
  4. items: std::iter::Skip<std::slice::Iter<'a, T>>,
  5. }
  6.  
  7. impl<'a, T> MyStructIterator<'a, T> {
  8. fn new(elements: &'a Vec<T>) -> MyStructIterator<'a, T> {
  9. let items = elements.iter();
  10. MyStructIterator {
  11. items: items.skip(3),
  12. }
  13. }
  14. }
  15.  
  16. impl<'a, T> Iterator for MyStructIterator<'a, T> {
  17. type Item = &'a T;
  18. fn next(&mut self) -> Option<Self::Item> {
  19. self.items.next()
  20. }
  21. }
  22.  
  23. struct MyStruct<T> {
  24. elements: Vec<T>,
  25. }
  26.  
  27. impl<'a, T> IntoIterator for &'a MyStruct<T> {
  28. type Item = &'a T;
  29. type IntoIter = MyStructIterator<'a, T>;
  30. fn into_iter(self) -> Self::IntoIter {
  31. MyStructIterator::new(&self.elements)
  32. }
  33. }
  34.  
  35. fn main() {
  36. let my_struct = MyStruct {
  37. elements: vec![
  38. "a".to_string(),
  39. "b".to_string(),
  40. "c".to_string(),
  41. "d".to_string(),
  42. "e".to_string(),
  43. ],
  44. };
  45.  
  46. let mut count = 0;
  47. for elem in &my_struct {
  48. println!("{}", elem);
  49. count += 1;
  50. }
  51. assert!(count == 2);
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement