簡體   English   中英

重命名匹配中的枚舉字段(rust)

[英]Rename enum fields in match (rust)

我在枚舉上有一個匹配塊,它的一個匹配案例在同一個枚舉上包含另一個匹配塊。 像這樣的東西:

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

有沒有辦法訪問內部匹配中的兩個attributes字段? 我看到了從內部匹配塊返回該字段的可能性,但是可以以更美觀的方式處理它嗎?

您可以像這樣重命名匹配的變量:

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

您可以在元組中同時匹配它們:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM