Cast from 'a type to 'static type, enforcing the original lifetime at runtime

⚓ Rust    📅 2025-08-11    👤 surdeus    👁️ 5      

surdeus

I need to use a function that accepts a generic argument T: SomeTrait + 'static.
But the argument I need to pass is not 'static, but has a lifetime 'a.
An example of code I need to complement:


trait SomeTrait {
    fn do_something(&self);
}

struct MyType<'a> {
    // ... something that uses 'a
}

impl<'a> SomeTrait for MyType<'a> {
    fn do_something(&self) {
        // ...
    }
}

fn my_code(v: MyType<'a>) {
    dependency(v);
}

fn dependency<T: SomeTrait + 'static>(v: T) {}

Clearly it is not possible to use this code as is, because MyType is not 'static. What i want to do instead is to enforce the lifetime of MyType at runtime: before 'a expires, I want to ensure that the reference that dependency function receives gets destroyed.

So, a rough sketch would be:


impl<'a> SomeTrait for Arc<Mutex<Option<MyType<'a>>>> {
    fn do_something(&self) {
        if self.lock().is_none() {
            return; // do nothing if the reference is destoyed
        }
        // ...
    }
}

fn my_code<'a>(v: MyType<'a>) {
    let my_type_rc = Arc::new(Mutex::new(Some(v)));

    dependency(my_type_rc.clone());
    
    // destroy the reference, to ensure that it cannot be accessed after the lifetime expires
    drop(my_type_rc.lock().take());
}

The code, of course, still doesn't work, since SomeTrait is still implemented for a type that is not 'static - but now it may be casted for 'static, and at runtime I ensure that the reference won't outlive the original lifetime 'a.

Is it possible to do in safe rust? If not, are there some crates that provide safe abstractions for safe temporary convertion from 'a types to 'static types?

Thanks.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed