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,
}
}
}
为什么会导致以下结果?
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,
}
推荐阅读
- angular - laravel angular没有将值传递给角度函数
- system-verilog - 为什么要在systemverilog中使用两次“new”?
- jenkins - Jenkins 主代理无法使用 EC2 插件连接到 Windows 从代理
- swift - 从 UIKit 视图运行场景的 SKAction
- reactjs - 反应中的串联get请求API调用
- fstar - 是否有 F* 的证明搜索功能?
- c# - 如何使用 c# 将 PDF 打印到 ZPL(斑马打印机)?
- c++ - C++ Windows 凭据提供程序错误屏幕
- css - 如何使用 CSS 将元素翻转 180 度?
- go - 将无限字节写入 bytes.Buffer