首页 > 解决方案 > 为什么将枚举变体与其名称和类型匹配不起作用?

问题描述

考虑以下示例:

pub enum DigitalWallet {
    WithMemo {
        currency: String,
        address: String,
        tag: String,
    },
    WithoutMemo {
        currency: String,
        address: String,
    },
}

impl<'a> DigitalWallet {
    fn getCurrency(self: &'a Self) -> &'a String {
        match self {
            DigitalWallet::WithMemo {
                currency: String, ..
            } => currency,
            DigitalWallet::WithoutMemo {
                currency: String, ..
            } => currency,
        }
    }
}

为什么会导致以下结果?

error[E0425]: cannot find value `currency` in this scope
  --> src/lib.rs:18:18
   |
18 |             } => currency,
   |                  ^^^^^^^^ not found in this scope

error[E0425]: cannot find value `currency` in this scope
  --> src/lib.rs:21:18
   |
21 |             } => currency,
   |                  ^^^^^^^^ not found in this scope

标签: rust

解决方案


你有语法错误。类型永远不会在模式中重复。

字段模式的语法是field_name: binding_name(并且field_name: field_name可以简化为field_name):

struct Foo {
    foo: i32,
}

fn main() {
    let foo = Foo { foo: 42 };

    match foo {
        Foo {
            foo: local_name_for_that_foo,
        } => {
            println!("{}", local_name_for_that_foo);
        }
    }
}

永久链接到操场

因此你需要

match self {
    DigitalWallet::WithMemo { currency, .. } => currency,
    DigitalWallet::WithoutMemo { currency, .. } => currency,
}

推荐阅读