首页 > 解决方案 > 模式匹配互斥体包装的特征实现者枚举的惯用方式?

问题描述

我正在使用enum_dispatch板条箱并想将我的一些MyBehaviorEnums 包装在 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();
                }
                _=>()
            }
        }
    }
}

标签: rust

解决方案


使用互斥体包装值时,请使用:

    match map.get_mut("First"){
        Some(mutex_impl_a)=>{
            match &*mutex_impl_a.lock().unwrap(){
                MyBehaviorEnum::MyImplementorA(a_instance)=>{
                    dbg!("got it!");
                }
                _=>()
            }
        }
        _=>()
    }

推荐阅读