rust - 如何放松对已知变体的嵌套匹配的非详尽模式检查?
问题描述
我如何说服 Rust 编译器内部match
表达式在这里很好,因为外部match
已经限制了可能的类型?
enum Op {
LoadX,
LoadY,
Add,
}
fn test(o: Op) {
match o {
Op::LoadX | Op::LoadY => {
// do something common with them for code reuse:
print!("Loading ");
// do something specific to each case:
match o {
// now I know that `o` can only be LoadX | LoadY,
// but how to persuade the compiler?
Op::LoadX => print!("x"), /* LoadX specific */
Op::LoadY => print!("y"), /* LoadY specific */
_ => panic!("shouldn't happen!"),
}
println!("...");
}
Op::Add => println!("Adding"),
}
}
fn main() {
test(Op::LoadX);
test(Op::LoadY);
test(Op::Add);
}
我尝试了两种方法,但似乎都不起作用。
命名或模式,然后使用该名称进行匹配:
match o { load@(Op::LoadX | Op::LoadY) => { // ... match load { // ... } }
这不是有效的 Rust 语法。
命名并绑定每个构造函数:
match o { load@Op::LoadX | load@Op::LoadY => { // ... match load { //... } }
这仍然不能满足详尽检查,因此出现相同的错误消息:
error[E0004]: non-exhaustive patterns: `Add` not covered --> src/main.rs:14:19 | 14 | match load { | ^ pattern `Add` not covered
有没有解决这个问题的惯用方法,或者我应该把panic!("shouldn't happen")
所有地方都放在哪里或重组代码?
解决方案
我认为你只需要重构你的代码,显然LoadX
并且LoadY
非常接近。所以我认为你应该创建一个重新组合它们的第二个枚举:
enum Op {
Load(State),
Add,
}
enum State {
X,
Y,
}
fn test(o: Op) {
match o {
Op::Load(state) => {
// do something common with them for code reuse
print!("Loading ");
// do something specific to each case:
match state {
State::X => print!("x"),
State::Y => print!("y"),
}
println!("...");
}
Op::Add => println!("Adding"),
}
}
fn main() {
test(Op::Load(State::X));
test(Op::Load(State::Y));
test(Op::Add);
}
这对我来说更有意义。我认为这是表达你想要的更好的方式。
推荐阅读
- c# - 使用分组属性建模和查询产品、属性、属性关系
- javascript - 处理 React 组件外部的单击以及如何向其添加动画?
- arrays - 有没有办法在 Swift 中将数组存储在数组中
- excel - 导致有关 ActiveWorkbook.Save 的运行时错误的代码未在我的 Workbook_Open() 事件中触发
- reactjs - 使用来自 refs 的信息来设置状态时的无限重新渲染循环
- embedded - 为什么链接描述文件会有多个节命令?
- json - 将回调保存为流星会话变量的一部分
- jenkins - 如何防止两个不同的 Jenkins 管道同时运行?
- python - 在python中将比较打印为数字而不是真或假
- javascript - Excel不显示俄语单词。它只适用于英文单词