现实世界里我们处理事情的逻辑都可以通过流程控制来描述,if number < 5
没有像 javascript 中 if(number < 5)
这样也是现代语言的特点。
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
在其他语言中,如果类型有值,则为默认为 true,而在 rust 中则必须是bool
型。
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
--> src/main.rs:21:8
|
21 | if number {
| ^^^^^^ expected bool, found integer
|
= note: expected type `bool`
found type `{integer}`
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}
在 rust 语言中,条件语句是有返回值的,这里根据条件会返回为 5,但是需要条件语句返回值的类型都是一致的,如果这个将 “hello” 替换掉 6,就会报错。
fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
zz999_9999_comp_ars000_3090_v283_rec709_v002_main_1003.jpeg
loop 是循环语句,可以使用break counter * 2
终止循环后并返回值。
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
assert_eq!(result, 20);
}
通过循环来遍历 a 集合,
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index = index + 1;
}
}
但是需要注意一下数组越界,如果 index 超出数组长度就会报错,所以尝试下面。
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
th.jpg
网友评论