Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function with lifetime from static context

I need to call a function with a lifetime specified on self from a static context like

impl  <'w> World<'w> {
    pub fn test_with_lifetime(&'w mut self) {
        println!("test with lifetime");
    }

    pub fn test(&mut self) {
        println!("test");
    }
}

pub fn main(){
    let mut world:World = World::new();

    let world_rc:Rc<RefCell<World<'static>>> = Rc::new(RefCell::new(world));

    let world_in_closure = Rc::clone(&world_rc);


    let bx = Box::new(move ||{

        if let Ok(mut borrowed_world) = world_in_closure.try_borrow_mut() {
            borrowed_world.test_with_lifetime();
        }
    });

    (bx)();
        
}

and if fails with ‘borrowed value does not live long enough…’ error.

So I have two questions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • what’s difference between &self and &'w self in function definition? Don’t they both effectively mean that object lives in the caller’s context?

  • is there a way to make it compile?

playground

>Solution :

pub fn test(&mut self) is not a shortcut of pub fn test(&'w mut self). Rather, it is a shortcut for pub fn test<'a>(&'a mut self).

The difference is where the lifetime is defined: 'w is a part of the type. It is decided by the one who create the instance. And by taking &'w mut self, you usually mean that this function can be called zero (if the instance does not live as long as 'w) or one (if it does) times. More than that it cannot, because because 'w is contained within the type it must be shorter than or equal to the lifetime of the instance. And after you call it with 'w one time, it is mutably borrowed for the rest of its life.

pub fn test<'a>(&'a mut self), on the other hand, means that the caller of the function decides about the lifetime. It can be (and usually is) as short as the whole call, and doesn’t need to be the whole instance’s lifetime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading