Hi ... This question is not asking why I shouldn't use a global variable or asking what is a much better way to do this besides using globals, I just want to first understand this exercise. Specifically I have two related questions on the topic:
First, how would I modify the syntax on lines 21 and or 28 here: Rust Playground In order to get this code to compile. What I am attempting to have here is a reference to an object that implements the trait FooInterface. Moreover, I want the global to be a mutable reference and I want the the object being pointed to to also be mutable. Is this possible with minor changes to my syntax at the playground.
The second question is about the lack of an error message about "statics require immutable values". I can not even include &mut DefaultFoo on my system which is running 1.40 nightly but the playground lets me write this syntax with out error. Is this syntax that was allowed before but now isn't?
I hope I've asked a question that makes sense and in a way that makes sense. Thanks.
@kornel Ok thanks. I see except .. I've actually tried the change with variants a few times before and the compiler would always complain about syntax or semantics. Here is the change at playground:
The answer seemed to be that pub static is not something rust does for a mutable data .. at least not the way I was trying to write it for an interface type. @kornel suggested
Mutex<Box<dyn FooInterface>>
which I think makes sense to me as the Mutex should mean only one thread is accessing the pointer at a time and so safety is provided at that level for global data. However, I can create this globally. I have a modified playground here for the original example:
Right now I am not even concerned about the mut aspect of the data pointed to by the box.
This code has evolved as I've tried many different ways to write this but the latest errors have rust complaining that I can't figure out how to describe to rust a lifetime for the FooInterface type. But when I give it one it either complains about the lifetime not being defined or about not being able to safely share between threads. I thought I'd read somewhere that dyn trait doesn't implement sync but since I am behind a Mutex I thought this code would be Ok. The code above produces the following error: