// 不变绑定x经过不变借用得到不变引用y
let x = 5;
let y = &x;
// let y: &i32 = &x;
// 可变绑定x经过可变借用得到可变引用y
let mut x = 5;
let y = &mut x;
// let y: &mut i32 = &mut x;
// let ref mut y = x;
*y += 1;
分支(branch)与循环(loop)
// if分支
let x = 5;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
let y = if x == 5 { 10 } else { 15 }; // y: i32
// loop循环
loop {
println!("Loop forever!");
}
// while循环
let mut done = false; // mut done: bool
while !done {
// if .. { done = true; }
}
// for循环
for x in 0..10 {
println!("{}", x); // x: i32
}
for (i,j) in (5..10).enumerate() {
println!("i = {} and j = {}", i, j);
}
let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}
// break 与 continue
loop {
// if .. { break; }
}
for x in 0..10 {
if x % 2 == 0 { continue; }
}
// 循环的标号
'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);
}
}