将相同变量绑定到共享特征的不同类型的模式 [英] Pattern binding the same variable to different types sharing a trait

查看:55
本文介绍了将相同变量绑定到共享特征的不同类型的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于通过特征共享某些行为的值的模式匹配问题.

I have a question about pattern matching on values sharing some behaviour through a trait.

我有一个包含两个变体的枚举,每个绑定值的不同类型,其中两种类型都实现了一个特征.我试图弄清楚是否可以创建一个单一的模式(E::VarA(x) | E::VarB(x) 形式),在其中我将两种类型绑定到单个常量,前提是我只对使用共享行为感兴趣.

I have an enum with two variants, each binding value of different types, where both types implement a trait. I'm trying to figure out whether it's possible to create a single pattern (of the E::VarA(x) | E::VarB(x) form) in which I bind both types to a single constant, provided I'm only interested in using the shared behaviour.

一个说明性示例:Playground:

trait T {
    fn f(&self) -> usize;
}

struct A;

impl T for A {
    fn f(&self) -> usize { 1 }
}

struct B;

impl T for B {
    fn f(&self) -> usize { 2 }
}

enum E {
    VarA(A),
    VarB(B),
}

fn unwrap(e: E) -> usize {
    match e {
        E::VarA(v) | E::VarB(v) => T::f(&v)
    }
}

fn main() {
    let val = E::VarA(A{});  
    println!("{}", unwrap(val));
}

代码显然无法编译,但它显示了我的意图.有没有办法让代码工作,最好比简单地拆分 pat1 | 更优雅pat2 =>...pat1 =>...;pat2 =>... ?

The code obviously does not compile, but it shows my intentions. Is there a way to make the code work, preferably more elegant than simply splitting the pat1 | pat2 => ... into pat1 => ... ; pat2 => ... ?

推荐答案

您可以制作一个宏来解包以匹配语句.

You can make a macro that unwraps to match statement.

trait T {
    fn f(&self) -> usize;
}

struct A;
impl T for A {
    fn f(&self) -> usize { 1 }
}

struct B;
impl T for B {
    fn f(&self) -> usize { 2 }
}

enum E {
    VarA(A),
    VarB(B),
}

macro_rules! unwrap {
    ($value:expr, $pattern:pat => $result:expr) => {
        match $value {
            E::VarA($pattern) => $result,
            E::VarB($pattern) => $result,
        }
    };
}

fn main() {
    let a = E::VarA(A{});
    let b = E::VarB(B{});

    println!("a:{} b:{}",
        unwrap!(a, ref sm => sm.f()),
        unwrap!(b, ref sm => sm.f()));

}

这篇关于将相同变量绑定到共享特征的不同类型的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆