How to get static lifetime?

In general, enough layers of Rc/RefCell will make anything work.

use std::rc::Rc;
use std::cell::RefCell;

#[derive(Clone)]
struct S1 { data: u32 }
impl S1 {
    fn new(data: u32) -> Self {
        S1 { data: data }
    }
}

struct S2 { s1: Rc<RefCell<S1>> }
impl S2 {
    fn new(s1: Rc<RefCell<S1>>) -> Self {
        S2 { s1: s1 }
    }
}
    
fn closed<F: Fn(&RefCell<S2>) + 'static>(f: &F) {}

fn main() {
    let s2 = Rc::new(S2::new(Rc::new(RefCell::new(S1 { data: 0 }))));
    let mut rs = s2.clone();
    closed(&move |_| { rs.s1.borrow_mut().data = 23;})
}

In specific cases it should be possible to simplify (or make less verbose) specific things. But describing code with words won't get us far.

1 Like