0

I'm using the enum_dispatch crate and want to wrap some of my MyBehaviorEnums 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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ANimator120
  • 2,556
  • 1
  • 20
  • 52
  • It looks like your question might be answered by the answers of [How to take ownership of T from Arc>?](https://stackoverflow.com/q/29177449/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 07 '21 at 20:27
  • `Mutex::into_inner(my_wrapped).unwrap().try_into()` – Shepmaster Jul 07 '21 at 20:29
  • 1
    Yes, your suggestion worked. – ANimator120 Jul 07 '21 at 20:33

0 Answers0