Work around for 'error: does not live long enough' when programmer knows it does live long enough

Hi,

This is for practice and learning about edge cases.

I've an object that I know lives long enough but I don't want to use Arc to improve performance. How this will be done in Rust? Following is example code: Rust Playground

Thanks in advance

Because Rust cannot prove that the thing lives long enough, the difference of having or not having that final join is too subtle for Rust to reason about. If you want to use scoped threads, like you showed in your example. Then use rayon::scope instead. That allows you to use local variables in you threads, and guarantees that the threads will be joined right before the end of the scope. If you want to live on the edge, you can use spawn_unchecked (this requires unsafe and nightly).

Unsafe is ok but there is no stable alternative?

Crossbeam scoped thread?

Stable alternative, without using crates like crossbeam, is:

let ilivelongenough_ref: &'static ThreadSafeStruct =
        unsafe { std::mem::transmute(&ilivelongenough) };

Of course, try safe alternatives before jumping to this.

1 Like

Isn't this a little safer?

let ilivelongenough_ref: &'static ThreadSafeStruct = 
    unsafe { &*(&ilivelongenough as *const _) };
2 Likes

There is, use rayon or crossbeam. I would use rayon because it is more suited to general use. Only use crossbeam if you have specific requirements.

1 Like

You probably mean unsafe { &*(&ilivelongenough as *const _) };. It’s a bit safer, cause you avoid transmute transmuting garbage that happens to have same size. But, for “trivial” cases like this, and if you’re reaching for unsafe, it’s a bit noisy for me. But yes, it’s a fair point and should be mentioned.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.