I'm new to Rust and coming from a C++ background. I feel explaining what I want to do with C++ terms is easier for me.
I want to create a global Hashmap what holds many objects (pointers)
during runtime, I give a key to the hashmap and get a weak pointer to an object in return.
The hashmap has the ownership of the pointers.
I don't know how to achieve this?
The hashmap is created with
static STATES: Lazy<HashMap<&String, Arc<dyn StateFunc>>> = Lazy::new(|| {
let hm = HashMap::new();
hm
});
getting:
12 | / static STATES: Lazy<HashMap<&String, Arc<dyn StateFunc>>> = Lazy::new(|| {
13 | | let hm = HashMap::new();
14 | | hm
15 | | });
| |___^ `dyn StateFunc` cannot be sent between threads safely
StateFunc is a trait:
trait StateFunc{
fn to_next(&self, c: char) -> Option<&Arc<dyn StateFunc>>;
}
I'm using a trait object, because I want to use it as the base class to achieve Polymorphism.
If to translate the above in C++ , I want:
class StateFunc{};
class StateA: public StateFunc{};
class StateB: public StateFunc{};
std::map<std::string, std:: shared_ptr <StateFunc>> globalHashMap{}
I only intent to use it in a single thread.