我想切换x
的许多可能情况,并且有一种情况(这里是x == 0
),我想检查一些其他代码的结果以确定下一步要做什么。一种可能性是比赛早退。
我会使用break
在C中进行此早期返回,但是Rust不允许这样做。 return
从父函数返回(在本例中为main()
),而不是仅从匹配项返回(即,末尾的println!
没有运行!)。
我可以否定子条件(此处为y == 0
)并缩进下面的所有代码-但我发现这很丑陋且难以理解。
对于我来说,将子条件放入比赛后卫是没有选择的,因为它太大了。
在Rust中这是否可行,或者有更好的选择(除了创建另一个子功能或其他解决方法)?
最小示例:
fn main() {
let x = 1;
match x {
1 => {
let y = 0;
/*
* do ev1l stuff to y that I don't want to put into the match-guard
* as it's simply too much.
*/
/* break early ... */
if y == 0 {break;} // > error: `break` outside of loop [E0268]
assert!(y != 0, "y was 0!");
/* do other stuff in here. */
}
_ => {}
}
println!("done matching");
}
我找到了Mixing matching, mutation, and moves in Rust-是吗?
match
embraces both imperative and functional styles of programming: you can continue usingbreak
statements, assignments, et cetera, rather than being forced to adopt an expression-oriented mindset.
我仍在学习Rust并且来自C语言,所以请多多包涵;-)
最佳答案
您可以将match
包装为仅运行一次并退出循环的loop
fn main() {
let x = 1;
loop { match x {
1 => {
let y = 0;
/*
* do ev1l stuff to y that I don't want to put into the match-guard
* as it's simply too much.
*/
/* break early ... */
if y == 0 { break; }
assert!(y != 0, "y was 0!");
/* do other stuff in here. */
}
_ => {}
} break; }
println!("done matching");
}
关于pattern-matching - Rust的比赛早破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63038815/