Rust - 循环
1、循环
1.1、loop循环
- loop关键字告诉Rust反复的执行一块代码,直到你停止
- 使用break关键字,告诉loop表达式何时停止
fn main() {
let mut number = 0;
let result = loop {
number += 1;
if number == 10 {
break number * 2;
}
};
}
1.2、while条件循环
- 另外一种常见的循环模式,每次执行循环体之前都判断一次条件
fn main() {
let mut number = 10;
while number !=0 {
println!("{}!",number);
number = number - 1;
}
println!("结束");
}
1.3、for循环
- for循环可以简洁紧凑
fn main() {
let number = [1,2,3,4,5,6,7,8];
for elemnt in number.iter() {
println!("the value is {}",elemnt);
}
}
推荐阅读: