Guest User

Untitled

a guest
Jan 17th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. use std::ops::*;
  2.  
  3. fn main()
  4. {
  5. let iter: MyIterator<f32> = MyIterator::new();
  6. for (i, val) in iter.take(10).enumerate() {
  7. println!("{} => {}", i, val);
  8. }
  9. }
  10.  
  11. struct MyIterator<T: MyType>
  12. {
  13. previous: T::InnerType,
  14. }
  15.  
  16. impl<T: MyType> MyIterator<T>
  17. {
  18. pub fn new() -> Self {
  19. MyIterator { previous: T::InnerType::ONE }
  20. }
  21. }
  22.  
  23. // `Add`, `Shl`, and `From` trait bounds only work when put here...
  24. impl<T: MyType> Iterator for MyIterator<T>
  25. {
  26. type Item = T;
  27.  
  28. fn next(&mut self) -> Option<Self::Item> {
  29. // Add one
  30. let plus_one = T::InnerType::from(self.previous + T::InnerType::ONE);
  31.  
  32. // Multiply by two
  33. let times_two = T::InnerType::from(plus_one << 1);
  34.  
  35. // Save state
  36. self.previous = times_two;
  37.  
  38. // Return value
  39. Some(T::from_inner(times_two))
  40. }
  41. }
  42.  
  43. trait MyType
  44. {
  45. // Want to put `Add`, `Shl`, and `From` trait bounds on InnerType here...
  46. type InnerType:
  47. One + Copy + Add + Shl<usize> +
  48. From<<Self::InnerType as Add>::Output> +
  49. From<<Self::InnerType as Shl<usize>>::Output>;
  50.  
  51. fn from_inner(val: Self::InnerType) -> Self;
  52. }
  53.  
  54. impl MyType for f32
  55. {
  56. type InnerType = u32;
  57.  
  58. fn from_inner(val: u32) -> f32 {
  59. val as f32
  60. }
  61. }
  62.  
  63. trait One
  64. {
  65. const ONE: Self;
  66. }
  67.  
  68. impl One for u32
  69. {
  70. const ONE: u32 = 1;
  71. }
Add Comment
Please, Sign In to add comment