走进Rust:流程控制

Rust大约 1837 字

if

if的条件必须是bool类型。

fn main() {
    let number = 3;
    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
    if number != 0 {
        println!("number was something other than zero");
    }
    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");
    }
}

let表达式中使用ififelse表达式内的值类型必须一致。

fn main() {
    let condition = false;
    let number = if condition {
        5
    } else {
        6
    };

    println!("The value of number is: {}", number);
}

loop

loop循环的一个作用是当你知道会失败时重试操作,例如检查一个线程是否完成他的任务。loop中可使用break关键字跳出循环,还可以返回想要的值以便后面的程序中使用该值。

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);
}

while

while循环有判断条件,当条件为true时循环继续执行,当为false时,循环终止。

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);

        number -= 1;
    }

    println!("LIFTOFF!!!");

    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("the value is: {}", a[index]);

        index += 1;
    }
}

for

for循环遍历数组。注意:遍历的是数组的迭代器iter,不是数组本身。

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("the value is: {}", element);
    }
}

使用..,生成Range类型。for循环遍历Range类型

fn main() {
    for number in 1..4 {
        println!("asc number={}", number);
    }
}

倒叙遍历Range,使用rev()函数逆转Range

fn main() {
    for number in (1..4).rev() {
        println!("desc number={}", number);
    }
}
阅读 136 · 发布于 2020-07-03

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批