退出块表达式?(类似于函数“返回") [英] Exit from a block expression? (similar to function "return")

查看:42
本文介绍了退出块表达式?(类似于函数“返回")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在到达最后一条语句之前从函数返回可以使用return"来完成,例如:

Returning from functions before reaching the last statement can be done using "return", for example:

fn example() -> i32 {
    if true {
        return 1;
    }

    0 // this line is never reached
}

可以用块表达式做类似的事情吗?示例:

Is it possible to do something similar with block expressions? Example:

let foo = {
    if true {
        *something to exit with 1*
    }

    0 // this line is never reached
};

感谢您的帮助.

附言我知道在这个简单的例子中我可以使用if-else"表达.我问的是一般的块表达式,而不是这个例子:)

P.S. I know in this simple example I could have used the "if-else" expression. I'm asking about block expressions in general, not this example in particular :)

推荐答案

对于稳定的 Rust,有一个众所周知的loop hack":

For stable Rust, there is a well known "loop hack":

fn main() {
    let foo = loop {
        if true {
            break 1;
        }

        break 0;
    };
}

对于 nightly,有 一个不稳定的特性 label_break_value 就是这样做的:

For nightly, there is an unstable feature label_break_value that does just that:

#![feature(label_break_value)]

fn main() {
    let foo = 'bar: {
        if true {
            break 'bar 1;
        }

        0 // this line is never reached
    };
}

通过查看 Github 问题,该功能是否会稳定下来似乎并不明显.它已经实施了 2 年多,但似乎没有足够的支持者来推进.

It doesn't seem obvious by looking at the Github issues whether this feature will ever be stabilized. It has been implemented for over 2 years, but it doesn't seem to have enough supporters to move forward.

这篇关于退出块表达式?(类似于函数“返回")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆