How do I use static lifetimes with threads?

You can’t convert &'a T into &'static T except by leaking memory. Luckily, this is not necessary at all. There is no reason to send borrowed pointers to the thread and keep the lines on the main thread. You don’t need the lines on the main thread. Just send the lines themselves, i.e. send String.

If access from multiple threads was necessary (and you don’t want to clone), use Arc<String> (in the future, Arc<str> may also work). This way the string is shared between threads, properly shared, so that it will be deallocated exactly when no thread uses it any more.

Sending non-'static references between threads is unsafe because you never know how long the other thread will keep using it, so you don’t know when the borrow expires and the object can be freed. Note that scoped threads don’t have this problem (which aren’t in 1.0 but are being redesigned as we speak) do allow this, but regular, spawned threads do.

'static is not something you should avoid, it is perfectly fine for what it does: Denoting that a value lives for the entire duration the program is running. But if that is not what you’re trying to convey, of course it is the wrong tool.

Leave a Comment