Why LocalKey::with is so restrictive?


#1

Hi,

LocalKey has two fundamental limitations:

  1. with accepts FnOnce
  2. with provides inner value as &T instead of &mut T. Requires RefCell to have normal mutable value.
    Both limit interaction of thread-local value and the scope which references it.
    Since value is thread-local, and lives nicely while thread is alive, those restrictions look a bit strange to me. Scoping access to function is perfectly fine, to avoid &'static reference leakage into other thread. But why not mutable?

Thanks

ANSWER

Sigh. I still need to learn a lot.
I’ll answer to my claims myself

  1. FnOnce is pretty much enough, it can access outer context nicely and without trouble - since it’s not 'static
  2. As fellow @gkoz pointed out, we need explicit RefCell to guard against nested calls - which can violate “no mutable aliasing” rule.

#2

FnOnce is the least limiting one in this context: Fn and FnMut inherit from it, every closure implements it.

[quote=“target_san, post:1, topic:3447”]
2. with provides inner value as &T instead of &mut T. Requires RefCell to have normal mutable value.
[/quote]Can’t you call with recursively? Had it used a RefCell it would just panic but this way you have a choice.


#3

The problem is, I need nested access. But some pieces of logic can’t be cleanly expressed in terms of borrow checker.
Explained a bit more here: RefCell: how to deceive borrow checker? . I need nested calls which aren’t exactly nested.