当前位置:网站首页>007、Rust中的控制流

007、Rust中的控制流

2020-12-06 18:02:30 ryanliue

1、if-else语句

let y = 0;
if(y == 1) {
    println!("y = 1");
} else {
    println!("y != 1");
}

再来看看if-else if-else语句:

let y = 0;
if(y == 1) {
    println!("y = 1");
} else if(y == 2) {
    println!("y == 2");
} else {
    println!("other");
}

在let中使用if:

let condition = true;
let x = if condition {
    5
} else {
    6
};
println!("x = {}", x);

2、循环
loop循环:

let mut counter = 0;
loop {
    println!("in loop");
    if counter == 10 {
        break;
    }
    counter += 1;
}

let result  = loop {
    counter += 1;
    if counter == 20 {
        break counter * 2;
    }
};
println!("result = {}", result);

while循环
 

let mut i = 0;
while i != 10 {
    i += 1;
}
println!("i = {}", i);

for循环:

let arr:[u32; 5] = [1, 2, 3, 4, 5];
for element in arr.iter() {
    println!("element = {}", element);
}
for element in &arr {
    println!("element = {}", element);
}

learn_con/src/main.rs完整源代码:
https://github.com/anonymousGiga/learn_rust/blob/master/learn_con/src/main.rs

版权声明
本文为[ryanliue]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/943779/blog/4777026