Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. type LongTraitObjType<'collection, 'data> =
  2. Box<dyn CreatesIterator<'collection, 'data, IteratorWithRef<'collection, 'data>> + 'data>;
  3.  
  4. fn main() {
  5. let data = 1;
  6.  
  7. // Works: concrete implementation:
  8. {
  9. let creates_iterator_impl = Box::new(CreatesIteratorImpl(vec![Wrapper(&data)]));
  10. let _ = creates_iterator_impl.iterate().count();
  11. }
  12.  
  13. // Doesn't work: same as above, but cast to a trait object.
  14. {
  15. let creates_iterator_dyn: LongTraitObjType =
  16. Box::new(CreatesIteratorImpl(vec![Wrapper(&data)]));
  17. let _ = creates_iterator_dyn.iterate().count();
  18. }
  19. }
  20.  
  21. #[derive(Clone)]
  22. struct Wrapper<'data>(&'data u32);
  23.  
  24. struct IteratorWithRef<'collection, 'data: 'collection> {
  25. reference: &'collection CreatesIteratorImpl<'data>,
  26. i: usize,
  27. }
  28. impl<'collection, 'data: 'collection> Iterator for IteratorWithRef<'collection, 'data> {
  29. type Item = Wrapper<'data>;
  30.  
  31. fn next(&mut self) -> Option<Self::Item> {
  32. if self.i < self.reference.0.len() {
  33. let ret = Some(self.reference.0[self.i].clone());
  34. self.i += 1;
  35. ret
  36. } else {
  37. None
  38. }
  39. }
  40. }
  41.  
  42. trait CreatesIterator<'collection, 'data, E>
  43. where
  44. 'data: 'collection,
  45. E: Iterator + 'collection,
  46. <E as Iterator>::Item: 'data,
  47. {
  48. fn iterate(&'collection self) -> E;
  49. }
  50.  
  51. struct CreatesIteratorImpl<'data>(Vec<Wrapper<'data>>);
  52.  
  53. impl<'collection, 'data: 'collection>
  54. CreatesIterator<'collection, 'data, IteratorWithRef<'collection, 'data>>
  55. for CreatesIteratorImpl<'data>
  56. {
  57. fn iterate(&'collection self) -> IteratorWithRef<'collection, 'data> {
  58. IteratorWithRef {
  59. reference: self,
  60. i: 0,
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement