考虑以下示例:
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
您语法错误。类型永远不会在模式中重复。
字段模式的语法为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,
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句