control_flow.md 1.7 KB
Newer Older
jackymao.com's avatar
jackymao.com 已提交
1 2
# 控制流

jackymao.com's avatar
jackymao.com 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
Rust 语言的逻辑控制流有: 
- if/else 条件分支
- loop 循环
- while 循环
- for in range 循环
- match 表达式
- if let
- while let

代码表示分别为:

```rust

if condition_a {}
else if condition_b {}
else {}

loop {}

'outer: loop {
    'innter: loop {
        ...
        break;
        // or
        break 'outer;
    }
}

loop {
    ...
    break counter * 2;
}

while condition_a {}

for n in 1..=100 {}

for name in names.iter() {}

match val {
    tuple_a => statement_a ;
    tuple_b => statement_b ;
    (x, y) if x = y => statement_c ;
    (x, y) => statement_d ;
    (Enum::A, Enum::B) => statement_e ;
    (n @ 1..=50, m @ 51..=100) => statement_f ;
    (Some(n), Some(m)) => statement_g ;
}

if let Some(i) = number {}
while let Some(i) = number {}

```

下列代码能正常运行的是:

## 答案

```rust

fn main() {
    let mut count = 0;
    'outer: loop {
        'inner: loop {
            if count >= 20 {
                break 'outer; 
            }
            count += 2;
        }
    }

    println!("Complete!");
}

```


## 选项

###

```rust

fn main() {
    let mut count = 0;
    'outer: loop {
        'inner: loop {
            if count <= 20 {
                count += 2;
                goto: 'inner; 
            }
        }
    }

    println!("Complete!");
}

```


### 

```rust

fn main() {
    for i in 0..=10 {
        if i == 10 {
            panic!("This never gonna happy");
        }
    }
}

```

###

```rust

fn main() {
    let guess = 51;
    let secret_number = 42;
    let result = if guess < secret_number {
        "Too small"
    } else if guess > secret_number {
        "Too big"
    } else {
        42
    };
    
    println!("{}", result);
}

```