I'm using the enum_dispatch crate and want to wrap some of my MyBehaviorEnum
s in a Mutex
. I'm able to call trait methods for Mutex<MyBehaviorEnum>
by using .lock().unwrap()
, but when I try and convert the enum back into the implementor, I get an error.
use core::convert::TryInto;
use enum_dispatch::enum_dispatch;
use std::sync::Mutex;
struct MyImplementorA {}
impl MyBehavior for MyImplementorA {
fn my_trait_method(&self) {}
}
struct MyImplementorB {}
impl MyBehavior for MyImplementorB {
fn my_trait_method(&self) {}
}
#[enum_dispatch]
enum MyBehaviorEnum {
MyImplementorA,
MyImplementorB,
}
#[enum_dispatch(MyBehaviorEnum)]
trait MyBehavior {
fn my_trait_method(&self);
}
fn main() {
let a: MyBehaviorEnum = MyImplementorA {}.into();
let my_wrapped = Mutex::new(a);
my_wrapped.lock().unwrap().my_trait_method();
let convert_back_to_implementor: Result<MyImplementorA, _> = my_wrapped.lock().unwrap().try_into();
}
gives the error:
error[E0277]: the trait bound `MyImplementorA: From<MutexGuard<'_, MyBehaviorEnum>>` is not satisfied
--> src\main.rs:33:93
|
33 | let convert_back_to_implementor: Result<MyImplementorA, _> = my_wrapped.lock().unwrap().try_into();
| ^^^^^^^^ the trait `From<MutexGuard<'_, MyBehaviorEnum>>` is not implemented for `MyImplementorA`
|
= note: required because of the requirements on the impl of `Into<MyImplementorA>` for `MutexGuard<'_, MyBehaviorEnum>`
= note: required because of the requirements on the impl of `TryFrom<MutexGuard<'_, MyBehaviorEnum>>` for `MyImplementorA`
= note: required because of the requirements on the impl of `TryInto<MyImplementorA>` for `MutexGuard<'_, MyBehaviorEnum>`
Is there a work around for this that will allow me convert the MutexGuard
into MyImplementorA
?