中断特定循环并返回一个值

huangapple go评论62阅读模式
英文:

Break out of specific loop and return a value

问题

我刚开始学习Rust,到达控制流部分时,我读到break可以返回一个值(循环是一个表达式),它还可以通过标签来退出特定的循环,例如break 'counting_up。所以我的问题是:

是否可以将这两者结合起来?也就是说,是否可以通过为循环命名来退出特定的循环 并且 返回一个值?

如果可以,那么如何分配和声明循环的语法是什么?

break的语法是什么?

以下是两种可能性,但都不是合法的语法:

fn main() {
    let mut count = 0;
    // 这样行吗?
    let result = 'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                // break count*10, 'counting_up;
                // 还是应该是:
                break 'counting_up, count*10;
            }
            remaining -= 1;
        }

        count += 1;
    };
    println!("End count = {count}");
}
英文:

I have just started studying Rust and reaching the control flow section I read break can return a value (the loop is an expression) and it can also break out of a specific loop using a label, e.g. break 'counting_up.

So my question is:

Is it possible to combine the two? i.e. break out of a specific loop by naming it and return a value as well?

If so, what is the syntax for assigning + declaring the loop?

What is the syntax of the break?

The following are two possibilities, but neither syntax compiles:

fn main() {
    let mut count = 0;
    // would this do?
    let result = 'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                // break count*10, 'counting_up;
                // or should it be:
                break 'counting_up, count*10;
            }
            remaining -= 1;
        }

        count += 1;
    };
    println!("End count = {count}");
}

答案1

得分: 8

是的,确实如此,没有分隔符,只是 break 'label value

英文:

Yes it is, and there is no separator, just break 'label value:

fn main() {
    let mut count = 0;
    let result = 'counting_up: loop {
        println!("count = {count}");
        let mut remaining = 10;

        loop {
            println!("remaining = {remaining}");
            if remaining == 9 {
                break;
            }
            if count == 2 {
                break 'counting_up count*10;
            }
            remaining -= 1;
        }

        count += 1;
    };
    println!("End count = {count}");
}

huangapple
  • 本文由 发表于 2023年7月3日 19:37:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定