loop
循环
多次执行同一段代码是很常用的,
loop
fn main() { // This program will never stop
loop {
}
}
因此,让我们告诉编译器何时会中断。
fn main() {
let mut counter = 0; // set a counter to 0
loop {
counter +=1; // increase the counter by 1
println!("The counter is now: {}", counter);
if counter == 5 { // stop when counter == 5
break;
}
}
}
The counter is now: 1
The counter is now: 2
The counter is now: 3
The counter is now: 4
The counter is now: 5
loop 命名
如果循环中有一个循环,则可以给它们命名。使用名称,您可以告诉'
(称为“刻度”)和 :
为其命名:
fn main() {
let mut counter = 0;
let mut counter2 = 0;
println!("Now entering the first loop.");
'first_loop: loop { // Give the first loop a name
counter +=1;
println!("The counter is now: {}", counter);
if counter > 9 { // Starts a second loop inside this loop
println!("Now entering the second loop.");
'second_loop: loop { // now we are inside `second_loop
println!("The second counter is now: {}", counter2);
counter2 +=1;
if counter2 == 3 {
break 'first_loop; // Break out of 'first_loop so we can exit the program
}
}
}
}
}
从循环返回
您还可以使用;
。这是一个带有循环和中断的示例,为
fn main() {
let mut counter = 5;
let my_number = loop {
counter +=1;
if counter % 53 == 3 {
break counter;
}
};
println!("{}", my_number);
}
在循环之前,我们声明了一个名为counter * 2
。循环之后,我们通过分号结束赋值给
while
fn main() {
let mut counter = 0;
while counter < 5 {
counter +=1;
println!("The counter is now: {}", counter);
}
}