为什么要“中断"?结束“循环"时不需要分号吗? [英] Why does "break" not need a semicolon when ending a "loop"?

查看:89
本文介绍了为什么要“中断"?结束“循环"时不需要分号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘录自第章锈书的3.5 :

我们使用 break 关键字,其值为 counter * 2 .循环后,我们使用分号结束将值分配给 result 的语句.

加上代码段:

  fn main(){让mut counter = 0;让结果=循环{计数器+ = 1;如果计数器== 10 {休息柜台* 2;}};println!(结果是{}",结果);} 

我了解它的工作原理以及为什么结果为20,但是我注意到,如果删除包含 break 关键字的行上的分号,则该程序是等效的.

为什么在这种情况下分号是可选的?

解决方案

一个简短的示例:

  let _:i32 =循环{如果属实 {休息3;//()}}; 

这只是分号不干扰预期结果的另一个示例.例如,插入分号会引入一个表达式语句,该表达式语句的计算结果为单元类型().随着 loop s和 if 表达式继续接受评估为相同类型()的代码块,因此所有类型都是一致的./p>

  let _:i32 =循环{如果属实 {打破3//!}}; 

如果分号被删除,则将 break 评估为

  • 是什么使用return语句和在Rust中省略分号之间的区别?
  • 如何静态断言函数的末尾不可达
  • Excerpt from Chapter 3.5 of the Rust Book:

    we use the break keyword with the value counter * 2. After the loop, we use a semicolon to end the statement that assigns the value to result.

    Plus the code snippet:

    fn main() {
        let mut counter = 0;
    
        let result = loop {
            counter += 1;
    
            if counter == 10 {
                break counter * 2;
            }
        };
    
        println!("The result is {}", result);
    }
    

    I understand how this works and why the result is 20, but I noticed that if I remove the semicolon on the line that contains the break keyword, the program is equivalent.

    Why is the semicolon optional in this case?

    解决方案

    A shorter example:

    let _: i32 = loop {
        if true {
            break 3; // ()
        }
    };
    

    That is just another example where the semi-colon does not interfere with the intended outcome. For one, the insertion of a semi-colon introduces an expression statement, which evaluates to the unit type (). As the loops and if expressions continue to admit a code block evaluating to the same type (), then all types are in conformance.

    let _: i32 = loop {
        if true {
            break 3 // !
        }
    };
    

    If the semi-colon is taken away, the break is evaluated to the never type !, which coerces to any other type. This means that it will fulfill any type expected by the outer scope. So all is well all the same, so long as you don't try to append any other statement before the end of the if block.

    Both break and return evaluate to !, as their side effects imply that the program will not go through with the natural workflow.

    See also:

    这篇关于为什么要“中断"?结束“循环"时不需要分号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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