我应该用 ; 结束一个表达式吗?在一个循环内? [英] Should I end an expression with ; inside a loop?
问题描述
我刚开始学习 Rust,经常遇到一些我找不到任何答案的问题.我真的不知道如何以及在哪里发布我的问题,所以我会尝试.
I just started learning Rust and I often have some questions that I can't find any answer. I don't really know how and where to post my question, so I'll try SO.
我开始阅读网站上的 Rust 文档,并做了猜谜游戏示例.
I started to read the Rust documentation on the website and I did the Guessing game example.
我意识到循环内的 match cmp
表达式可以变成一个语句,一切仍然有效.所以我想知道为什么和哪个版本应该是首选?
I realized that the match cmp
expression inside the loop could be turned into a statement and everything still works. So I wonder why and what version should really be preferred?
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
} // <=== here should it be ended as statement (;) or not?
}
}
推荐答案
match
、if
、loop
和其他具有 {}
块由 Rust 编译器特别处理.当这些表达式作为表达式语句出现时,即不是作为更大表达式的一部分,并且有块的表达式的类型是()
,你不必把;
放在后面将其与以下语句分开.
match
, if
, loop
, and other expressions that have {}
blocks are treated specially by the Rust compiler. When these expressions occur as expression statements, that is, not as part of a larger expression, and the type of the expression that has the block is ()
, you do not have to put ;
after it to separate it from a following statement.
这不是没有块的表达式语句的情况,它总是必须通过;
与下面的语句(如果存在)分开,即使它们的类型是()
.
This is not the case for expression statements without blocks, which always must be separated from the following statement (if one exists) by ;
, even if their type is ()
.
因为这个规则存在,在Rust中通常不把;
放在match
之后,if
、unsafe
等仅用于副作用,或在 for
和 while
循环(它们是总是只用于副作用,因为它们总是返回 ()
).
Because this rule exists, it is usual in Rust not to put ;
after match
, if
, unsafe
, etc. when they are used only for side effects, or after for
and while
loops (which are always used only for side effects, since they always return ()
).
也就是说,rustfmt 和 Clippy 似乎都可以使用额外的 ;
,所以如果您出于审美原因更喜欢它,那么使用它就不太可能冒犯任何人.
That said, both rustfmt and Clippy seem to be fine with the extra ;
, so if you prefer it there for aesthetic reasons, you're unlikely to offend anyone by using it.
这篇关于我应该用 ; 结束一个表达式吗?在一个循环内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!