解构嵌套枚举时如何防止"match hell"?



有没有一种更好/更干净的方法可以在不引入嵌套地狱式match调用的情况下销毁rust枚举?

我目前销毁多个嵌套枚举的方法如下:

enum Top {
Middle(Middle)
}
enum Middle {
Bottom(Bottom)
}
enum Bottom {
Value(i32)
}
fn foo () -> Top {
Top::Middle(Middle::Bottom(Bottom::Value(17)))
}
fn main() {
match foo() {
Top::Middle(middle) => match middle {
Middle::Bottom(bottom) => match bottom {
Bottom::Value(value) => println!("Value {}", value)
}
}
}
}

或Rust Playground

如果我增加";层";在CCD_ 2和CCD_;更硬";维护。

是否存在";线性";在不丢失match提供的所有功能的情况下处理嵌套枚举的方法(例如,当某些匹配丢失时通知等(?

我在找类似的东西

// cut
fn main() {
match foo() {
Top::Middle(Middle::Bottom(Bottom::Value(value))) => println!("Value {}", value)
}
}

感谢@Caesar

我正在寻找类似的东西

fn main() {
match foo() {
Top::Middle(Middle::Bottom(Bottom::Value(value))) => println!("Value >{}", value)
}
}

我的假设是正确的。此代码有效。参见操场

是否存在";线性";在不丢失匹配提供的所有功能的情况下处理嵌套枚举的方法(例如,当某些匹配丢失时通知等(?

我想知道";线性";方法会通知是否有遗漏的枚举?是的,它会通知。

我在Bottom枚举中又添加了一个选项

// cut
enum Bottom {
Value(i32),
Data(String)
}
// cut

并且在编译时显示错误

Compiling playground v0.0.1 (/playground)
error[E0004]: non-exhaustive patterns: `Middle(Bottom(Data(_)))` not covered
--> src/main.rs:20:11
|
20 |     match foo() {
|           ^^^^^ pattern `Middle(Bottom(Data(_)))` not covered
|
note: `Top` defined here
--> src/main.rs:3:5
|
2  | enum Top {
|      ---
3  |     Middle(Middle)
|     ^^^^^^ not covered
= note: the matched value is of type `Top`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
21 ~         Top::Middle(Middle::Bottom(Bottom::Value(value))) => println!("Value {}", value),
22 +         Middle(Bottom(Data(_))) => todo!()
|
For more information about this error, try `rustc --explain E0004`.
error: could not compile `playground` due to previous error

参见操场

最新更新