Advertisement
Guest User

Untitled

a guest
May 19th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. /// Represents some struct that holds references inside
  2. #[derive(Debug)]
  3. struct MyValue<'a> {
  4. number: &'a u32,
  5. }
  6.  
  7. /// There are many structs similar to `MyValue` and there is a
  8. /// trait common to them all that can create them.
  9. impl<'a> From<&'a u32> for MyValue<'a> {
  10. fn from(value: &'a u32) -> Self {
  11. MyValue {
  12. number: value,
  13. }
  14. }
  15. }
  16.  
  17. /// This produces objects that hold references into it. So the
  18. /// object must be dropped first before any new one is made.
  19. trait Producer<'a, T: 'a> {
  20. fn make(&'a mut self) -> T;
  21. }
  22.  
  23. struct MyProducer<'a, T: 'a + From<&'a u32>> {
  24. number: u32,
  25. _phantom: std::marker::PhantomData<&'a T>,
  26. }
  27.  
  28. impl<'a, T: 'a + From<&'a u32>> MyProducer<'a, T> {
  29. fn new() -> Self {
  30. Self {
  31. number: 0,
  32. _phantom: std::marker::PhantomData::default(),
  33. }
  34. }
  35. }
  36.  
  37. impl<'a, T: From<&'a u32>> Producer<'a, T> for MyProducer<'a, T> {
  38. fn make(&'a mut self) -> T {
  39. self.number += 1;
  40. T::from(&self.number)
  41. }
  42. }
  43.  
  44. fn main() {
  45. let mut producer = MyProducer::<MyValue>::new();
  46.  
  47. println!("made this: {:?}", producer.make());
  48. println!("made this: {:?}", producer.make());
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement