pattern-matching - Rust的比赛早破

标签 pattern-matching rust match break

我想切换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 using break 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/

相关文章:

string - 使用 awk 对单词进行特定于行的重新排序

rust - 从行迭代器创建单词迭代器

lambda - 将函数作为参数传递给另一个函数

list - Scala 列表匹配

regex - 从文件加载正则表达式并在 Perl 中匹配组

search - 替换某些字符,但不替换匹配项中找到的字符

scala - 为什么 Scala 要求模式变量是线性的?

rust - Rust 中的动态类型实体组件系统

enums - 我如何只匹配枚举的部分而不是所有变体?

macros - 笛卡尔积匹配