NLinker icon

Lifetimes for functions

NLinker | PRO | 07/15/18 04:18:23 AM UTC | 0 ⭐ | 976 👁️ | Never ⏰ | []
Rust |

930 B

|

None

|

0 👍

/

0 👎

use std::rc::Rc;
use std::ops::Deref;
 
type CallBack = Fn(f32) -> f32;
 
struct Caller<T>
        where T: Deref<Target = Box<CallBack>> {
    call_back: T,
}
 
impl<T> Caller<T> 
        where T: Deref<Target = Box<CallBack>> {
    fn new(call_back: T) -> Caller<T> {
        Caller {call_back: call_back}
    }
 
    fn call(&self, x: f32) -> f32 {
        (*self.call_back)(x)
    }
}
 
fn main() {
    let caller = {
        // function is used by `Caller` and `main()` => shared resource
        // solution: `Rc`
        let func_obj = Box::new(|x: f32| 2.0 * x) as Box<CallBack>;
        let func = Rc::new(func_obj); 
        let caller = Caller::new(func.clone());
        
        // we also want to use func now
        let _y = func(3.0);
        
        caller
    };
    
    // func survives because it is referenced through a `Box` in `caller`
    let y = caller.call(1.0);
    assert_eq!(y, 2.0);
}

Comments