为什么要“中断"?结束“循环"时不需要分号吗? [英] Why does "break" not need a semicolon when ending a "loop"?
问题描述
摘录自第章锈书的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//!}};
如果分号被删除,则将 Excerpt from Chapter 3.5 of the Rust Book: we use the Plus the code snippet: 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 Why is the semicolon optional in this case? A shorter example: 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 If the semi-colon is taken away, the Both See also: 这篇关于为什么要“中断"?结束“循环"时不需要分号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! break
评估为
break
keyword with the value counter * 2
. After the loop, we use a semicolon to end the statement that assigns the value to result
.fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
break
keyword, the program is equivalent.let _: i32 = loop {
if true {
break 3; // ()
}
};
()
. As the loop
s 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 // !
}
};
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.break
and return
evaluate to !
, as their side effects imply that the program will not go through with the natural workflow.