循环
for
for var in iterator {
code
}for x in 0..10 {
println!("{}", x); // x: i32
}0
1
2
3
4
5
6
7
8
9while
loop
break 和 continue
label
Last updated
for var in iterator {
code
}for x in 0..10 {
println!("{}", x); // x: i32
}0
1
2
3
4
5
6
7
8
9Last updated
// C 语言的 for 循环例子
for (x = 0; x < 10; x++) {
printf( "%d\n", x );
}for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}", i, j);
}i = 0 and j = 5
i = 1 and j = 6
i = 2 and j = 7
i = 3 and j = 8
i = 4 and j = 9let lines = "Content of line one
Content of line two
Content of line three
Content of line four".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}0: Content of line one
1: Content of line two
2: Content of line three
3: Content of line fourwhile expression {
code
}let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}while true {
// do something
}loop {
// do something
}let mut a;
loop {
a = 1;
// ... break ...
}
do_something(a)let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}let mut x = 5;
loop {
x += x - 3;
println!("{}", x);
if x % 5 == 0 { break; }
}for x in 0..10 {
if x % 2 == 0 { continue; }
println!("{}", x);
}1
3
5
7
9'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 { continue 'outer; } // continues the loop over x
if y % 2 == 0 { continue 'inner; } // continues the loop over y
println!("x: {}, y: {}", x, y);
}
}