Skip to content

Latest commit

 

History

History
108 lines (81 loc) · 1.57 KB

04.控制流.md

File metadata and controls

108 lines (81 loc) · 1.57 KB

控制流

let 语句中使用 if

因为 if 是一个表达式,我们可以在 let 语句的右侧使用它:

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

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

注意 if 的每个分支的可能的返回值都必须是相同类型。

循环语句

loop 循环

fn main() {
    loop {
        println!("again!");
    }
}

可以使用 break 关键字停止循环并返回其值

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

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

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

while 循环

fn main() {
    let mut number = 3;

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

        number = number - 1;
    }

    println!("LIFTOFF!!!");
}

for 循环

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

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

for 循环 中 IntoIterator 语法糖

let values = vec![1, 2, 3, 4, 5];

for x in values {
    println!("{}", x);
}

// de-sugars

let values = vec![1, 2, 3, 4, 5];
{
    let result = match IntoIterator::into_iter(values) {
        mut iter => loop {
            let next;
            match iter.next() {
                Some(val) => next = val,
                None => break,
            };
            let x = next;
            let () = { println!("{}", x); };
        },
    };
    result
}