rust控制流

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");
    }

    //可以在let语句右侧使用
    let condition = true;
    let number = if condition {
        //注意这是个表达式没有分号
        5
    }else{
        //else的类型必须和if的一致
        6
    };
    println!("the value of number is {}",number);
    
    //循环有loop,for,while
    //loop可以通过break返回一个值
    let mut counter = 0;

    let result = loop {
        counter += 1;

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

    println!("The result is {}", result);
    let a = [10,20,30,40];
    for element in a.iter() {
        println!("the value  is: {}",element)
    }

    for number in (1..4).rev() {
        println!("{}!",number);
    }

}

相关推荐