Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. /*
  2. I want make_closure to create a boxed closure which can accept an &i32
  3. reference with any lifetime, convert it to a T, and perform further processing
  4. on that T. It must be possible for T to be another &i32 with the same lifetime
  5. as the input &i32, i.e., it must be possible for the "conversion" to be a
  6. no-op.
  7. */
  8.  
  9. fn make_closure<'a, T>() -> Box<dyn Fn(&'a i32)>
  10. where
  11. T: 'a + std::fmt::Debug + CreateFromI32Ref<'a>
  12. {
  13. Box::new(move |i32_ref: &i32| {
  14. T::create_from_i32_ref(i32_ref).process()
  15. })
  16. }
  17.  
  18. trait CreateFromI32Ref<'a>: Sized {
  19. fn create_from_i32_ref(i32_ref: &'a i32) -> Self;
  20. fn process(self) {
  21. println!("processing...")
  22. }
  23. }
  24.  
  25. impl<'a> CreateFromI32Ref<'a> for i32 {
  26. fn create_from_i32_ref(i32_ref: &'a i32) -> i32 {
  27. *i32_ref
  28. }
  29. }
  30.  
  31. impl<'a> CreateFromI32Ref<'a> for &'a i32 {
  32. fn create_from_i32_ref(i32_ref: &'a i32) -> &'a i32 {
  33. i32_ref
  34. }
  35. }
  36.  
  37. /*
  38. It seems self-evident that CreateFromI32Ref is implemented for all possible
  39. `&'a i32` types, but the second make_closure fails to compile, with the error
  40. "the trait `for<'a> CreateFromI32Ref<'a>` is not implemented for `&i32`"
  41. */
  42.  
  43. fn main() {
  44. make_closure::<i32>()(&100i32);
  45. make_closure::<&i32>()(&100i32);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement