Guest User

Untitled

a guest
May 27th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. use std::ops::Index;
  2.  
  3. trait MyTrait {
  4. fn foo(&self);
  5. }
  6.  
  7. struct TypeA;
  8.  
  9. impl MyTrait for TypeA {
  10. fn foo(&self) {
  11. println!("Foo A");
  12. }
  13. }
  14.  
  15. struct TypeB;
  16.  
  17. impl MyTrait for TypeB {
  18. fn foo(&self) {
  19. println!("Foo B");
  20. }
  21. }
  22.  
  23. struct Container<'a, T1: 'a, T2: 'a> {
  24. some_foo: &'a [T1],
  25. some_more_foo: &'a [T2],
  26. }
  27.  
  28. impl<'a, T1, T2> Index<usize> for Container<'a, T1, T2>
  29. where
  30. T1: MyTrait,
  31. T2: MyTrait,
  32. {
  33. type Output = MyTrait;
  34.  
  35. fn index(&self, index: usize) -> &MyTrait {
  36. let foo_len = self.some_foo.len();
  37. if index < foo_len {
  38. &self.some_foo[index]
  39. }
  40. else {
  41. &self.some_more_foo[index]
  42. }
  43. }
  44. }
  45.  
  46. fn main() {
  47. let a = [TypeA {}, TypeA {}, TypeA {}];
  48. let b = [TypeB {}, TypeB {}, TypeB {}];
  49.  
  50. let c = Container { some_foo: &a, some_more_foo: &b };
  51. c[0].foo();
  52. }
Add Comment
Please, Sign In to add comment