Почему сопоставление вариантов enum с их именами и типами не работает? - PullRequest
1 голос
/ 13 января 2020

Рассмотрим следующий пример:

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

1 Ответ

5 голосов
/ 13 января 2020

У вас неверный синтаксис. Типы никогда не повторяются в шаблонах.

Синтаксис для шаблона поля: field_name: binding_namefield_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,
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...