Amanieu / thread_local-rs

Per-object thread-local storage for Rust

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`ThreaLocal::get_or` with possibility of returning a `Result`?

dpc opened this issue · comments

I want to have thread local values, that when not initialized, will lock global mutex and clone shared value. However the locking can fail, and using get_or I have no way to return Result<T, E> or anything like that. Am I missing something, and if not - could such method be added?

Would using a ThreadLocal<Result<T, E>> be sufficient for this?

That will be my workaround for now, I guess, but after I acquire the thread-local clone of the type, there's no way it can become Err so storing it in Result is a waste.

Hmm, I think one possibility would be to add a set method. You would then be able to do something like this:

if tls.get().is_none() {
    match lock_stuff() {
        Ok(x) => tls.set(x),
        Err(..) => ..,
    }
}

That would work with me. Though I'd prefer:

fn get_or_try<F, E>(&self, create: F) -> Result<&T, E>
where F: FnOnce() -> Result<Box<T>, E>

In case value is initialized it would create OK(&T), otherwise return whatever create returned.

Ok, that sounds reasonable.