rust - 模式匹配互斥体包装的特征实现者枚举的惯用方式?
问题描述
我正在使用enum_dispatch板条箱并想将我的一些MyBehaviorEnum
s 包装在 a 中Mutex
,然后将它们插入到 aHashMap
中。MyBehaviorEnum
如果没有 Mutex,当我从 HashMap 获取项目时,我可以轻松地对不同的值进行模式匹配。但是我不确定当值被包裹在互斥体中时如何进行这种匹配MyHeaviorEnum
,或者一种惯用的方法可能是什么样的。
enum_dispatch = "0.3.7"
use core::convert::TryInto;
use enum_dispatch::enum_dispatch;
use std::sync::Mutex;
use std::collections::HashMap;
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() {
//No Mutex wrapper
let a: MyBehaviorEnum = MyImplementorA {}.into();
let a2: MyBehaviorEnum = MyImplementorA {}.into();
let mut map = HashMap::new();
map.insert("First", a);
map.insert("Second", a2);
match map.get_mut("First"){
Some(MyBehaviorEnum::MyImplementorA(a_instance)) =>{
a_instance.my_trait_method();
}
_=>()
}
//Implementor enum values are wrapped in Mutex then inserted into HashMap
let a: MyBehaviorEnum = MyImplementorA {}.into();
let a2: MyBehaviorEnum = MyImplementorA {}.into();
let mut map = HashMap::new();
map.insert("First", Mutex::new(a));
map.insert("Second", Mutex::new(a2));
match map.get_mut("First"){
Some(mutex_impl_a)=>{
match Mutex::into_inner(mutex_impl_a){
Ok(MyBehaviorEnum::MyImplementorA(a_instance)) =>{
a_instance.my_trait_method();
}
_=>()
}
}
}
}
解决方案
使用互斥体包装值时,请使用:
match map.get_mut("First"){
Some(mutex_impl_a)=>{
match &*mutex_impl_a.lock().unwrap(){
MyBehaviorEnum::MyImplementorA(a_instance)=>{
dbg!("got it!");
}
_=>()
}
}
_=>()
}
推荐阅读
- python - Matplotlib - 避免轮廓拦截边界
- logging - 我可以仅使用 PM2 为特定日志添加时间戳吗?
- javascript - 如何在使用 GET 功能的 POST 请求后更改窗口位置的方向
- react-native - 按钮未显示在视图中
- javascript - 根据房间可用性,我想在日历中显示可用
- sql - 由于“或”条件,蜂巢中的交叉产品
- php - 如何检查和获取价值并在 html 中显示
- php - 无法将值分配给错误数组以处理 PHP 中的错误
- javascript - 如何使我的光滑滑块按应有的方式工作?
- react-native - React Native 为一侧创建三角形布局