Advertisement
NLinker

Lifetimes for functions

Jul 14th, 2018
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.93 KB | None | 0 0
  1. use std::rc::Rc;
  2. use std::ops::Deref;
  3.  
  4. type CallBack = Fn(f32) -> f32;
  5.  
  6. struct Caller<T>
  7.         where T: Deref<Target = Box<CallBack>> {
  8.     call_back: T,
  9. }
  10.  
  11. impl<T> Caller<T>
  12.         where T: Deref<Target = Box<CallBack>> {
  13.     fn new(call_back: T) -> Caller<T> {
  14.         Caller {call_back: call_back}
  15.     }
  16.  
  17.     fn call(&self, x: f32) -> f32 {
  18.         (*self.call_back)(x)
  19.     }
  20. }
  21.  
  22. fn main() {
  23.     let caller = {
  24.         // function is used by `Caller` and `main()` => shared resource
  25.         // solution: `Rc`
  26.         let func_obj = Box::new(|x: f32| 2.0 * x) as Box<CallBack>;
  27.         let func = Rc::new(func_obj);
  28.         let caller = Caller::new(func.clone());
  29.        
  30.         // we also want to use func now
  31.         let _y = func(3.0);
  32.        
  33.         caller
  34.     };
  35.    
  36.     // func survives because it is referenced through a `Box` in `caller`
  37.     let y = caller.call(1.0);
  38.     assert_eq!(y, 2.0);
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement