为什么匹配枚举变体及其名称和类型不起作用?

dro*_*te7 1 rust

考虑以下示例:

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,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么会出现以下情况?

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,
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mca*_*ton 5

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

字段模式的语法是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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

固定链接到操场

因此你需要

match self {
    DigitalWallet::WithMemo { currency, .. } => currency,
    DigitalWallet::WithoutMemo { currency, .. } => currency,
}
Run Code Online (Sandbox Code Playgroud)