if else
if else语句块是表达式
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
for
用法
使用 for 时我们往往使用集合的引用形式(比如我们这里使用了 container 的引用):
for item in &container {
// ...
}
如果不使用引用的话,所有权会被转移(move)到 for 语句块中,后面就无法再使用这个集合了):
for item in container {
// ...
}
对于实现了 copy 特征的数组(例如 [i32; 10] )而言, for item in arr 并不会把 arr 的所有权转移,而是直接对其进行了拷贝,因此循环之后仍然可以使用 arr 。
转移所有权
for item in collection
不可变借用
for item in &collection
for item in collection.iter()
可变借用
for item in &mut collection
for item in collection.iter_mut()
遍历数组
rust中的array的[]会进行越界检查,
上述的for container则不会触发这种检查,因为编译器会在编译时就完成分析并证明这种访问是合法的
所以遍历数组使用for container方式开销更小
loop
loop 是一个表达式
break continue
break 可以单独使用,也可以带一个返回值
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
当有多层循环时,你可以使用 continue 或 break 来跳到外层指定的循环。要实现这一点,外部的循环必须拥有一个标签 ‘label, 然后在 break 或 continue 时指定该标签
fn main() {
let mut count = 0;
'outer: loop {
'inner1: loop {
if count >= 20 {
// 这只会跳出 inner1 循环
break 'inner1; // 这里使用 `break` 也是一样的
}
count += 2;
}
count += 5;
'inner2: loop {
if count >= 30 {
break 'outer;
}
continue 'outer;
}
}
assert!(count == 30)
}