首页 > 解决方案 > 重命名匹配中的枚举字段(锈)

问题描述

我在枚举上有一个匹配块,其中一个匹配案例在同一个枚举上包含另一个匹配块。像这样的东西:

fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
            Scenario::Step { attributes, .. } => {
                match scenario {
                    Scenario::Step { attributes,.. } => {

有没有办法访问attributes内部匹配中的两个字段?我看到了从内部匹配块返回该字段的可能性,但是可以以更美观的方式处理它吗?

标签: rustenumsmatch

解决方案


您可以像这样重命名匹配的变量:

fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
            Scenario::Step { attributes: attrs1, .. } => {
                match scenario {
                    Scenario::Step { attributes: attrs2,.. } => {
                        // do something with attrs1 and attrs2

更好的是,你可以在一个元组中匹配它们:

fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match (self, scenario) {
            (Scenario::Step { attributes: attrs1, .. }, Scenario::Step { attributes: attrs2,.. }) => {
                // do something with attrs1 and attrs2

推荐阅读