I'm confused about the usage of Rust around static variables with Box Traits.
trait ContextBase {}
struct ContextA {}
impl ContextBase for ContextA {}
struct ContextB {}
impl ContextBase for ContextB {}
lazy_static! {
static ref GLOBAL_CONTEXT: HashMap<&'static str, Box<ContextBase>> = HashMap::new();
}
I want to allow Context
which implements the ContextBase
traits. But compile results are like this.
error[E0277]: `(dyn context::ContextBase + 'static)` cannot be shared between threads safely
--> src/context.rs:19:1
|
19 | / lazy_static! {
20 | | static ref GLOBAL_CONTEXT: HashMap<&'static str, Box<ContextBase>> = HashMap::new();
21 | | }
| |_^ `(dyn context::ContextBase + 'static)` cannot be shared between threads safely
|
= help: the trait `std::marker::Sync` is not implemented for `(dyn context::ContextBase + 'static)`
= note: required because of the requirements on the impl of `std::marker::Sync` for `std::ptr::Unique<(dyn context::ContextBase + 'static)>`
= note: required because it appears within the type `std::boxed::Box<(dyn context::ContextBase + 'static)>`
= note: required because it appears within the type `(&'static str, std::boxed::Box<(dyn context::ContextBase + 'static)>)`
= note: required because of the requirements on the impl of `std::marker::Sync` for `hashbrown::raw::RawTable<(&'static str, std::boxed::Box<(dyn context::ContextBase + 'static)>)>`
= note: required because it appears within the type `hashbrown::map::HashMap<&'static str, std::boxed::Box<(dyn context::ContextBase + 'static)>, std::collections::hash_map::RandomState>`
= note: required because it appears within the type `std::collections::HashMap<&'static str, std::boxed::Box<(dyn context::ContextBase + 'static)>>`
= note: required by `lazy_static::lazy::Lazy`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
Can anyone help me resolve this issue??