3 ms·
One much better solution than using any globals is passing an opaque context object through the call chain, much in the way many Go libraries do it. This allows
by jupp0r 6y ago
One much better solution than using any globals is passing an opaque context object through the call chain, much in the way many Go libraries do it. This allows you to scope what APIs have access to what parts of the context and prevents its implementation details to be splattered all over the place. It also allows for mocking parts of the runtime in unit tests and makes synchronization across threads an implementation detail of the APIs that downcast the context (as opposed to Arc<RwLock<T>>, which is not exactly a pleasure to use).
Once you do pass context everywhere, it's easy to add new things to it without incurring the cost of adding a new method parameter.
Of course this can be (and has been) abused and you need to use it carefully and as little as possible. I still think it's orders of magnitude better than mutable global variables.