rust - 如何将 enum_dispatch 的 try_into() 与 Mutex 一起使用?
问题描述
我正在使用enum_dispatch板条箱并想将我的一些MyBehaviorEnum
s 包装在Mutex
. 我可以Mutex<MyBehaviorEnum>
通过 using调用特征方法.lock().unwrap()
,但是当我尝试将枚举转换回实现者时,出现错误。
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();
}
给出错误:
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>`
是否有解决此问题的方法可以让我将其转换MutexGuard
为MyImplementorA
?