112 lines
2.4 KiB
Plaintext
112 lines
2.4 KiB
Plaintext
---
|
|
title: Control Flow
|
|
description: Directing execution with expression-based logic, pattern matching, and traditional loop structures.
|
|
icon: Split
|
|
---
|
|
|
|
Control flow in Mist provides a bridge between C-style procedural logic and Rust's expression-oriented design. Blocks, if statements, while/for/loop loops, and match expressions all support statement bodies.
|
|
|
|
## Conditionals
|
|
|
|
The `if` statement evaluates a boolean expression:
|
|
|
|
```mist
|
|
if (score > 50) {
|
|
println!("Pass");
|
|
} else if (score == 50) {
|
|
println!("Borderline");
|
|
} else {
|
|
println!("Fail");
|
|
}
|
|
|
|
// Single-statement body (no braces needed)
|
|
if (is_active) println!("Running");
|
|
|
|
// Expression body (implicit return)
|
|
let result = if (valid) { "ok" } else { "err" };
|
|
```
|
|
|
|
## Match
|
|
|
|
The `match` statement provides exhaustive pattern matching with support for multiple patterns per arm via `|`:
|
|
|
|
```mist
|
|
match (task_state) {
|
|
TaskState::Pending => { println!("Queued"); }
|
|
TaskState::Failed { reason, code } => {
|
|
println!("Error {}: {}", code, reason);
|
|
}
|
|
TaskState::NotResponding | TaskState::Progress => {
|
|
draw_loading();
|
|
}
|
|
_ => { println!("Other state"); }
|
|
}
|
|
```
|
|
|
|
Patterns support destructuring, or-patterns, and wildcards:
|
|
|
|
```mist
|
|
let x = 2;
|
|
let result;
|
|
|
|
match (x) {
|
|
1 => { result = 10; }
|
|
2 => { result = 20; }
|
|
3 => { result = 30; }
|
|
_ => panic!();
|
|
}
|
|
```
|
|
|
|
## Loops
|
|
|
|
### Loop
|
|
|
|
An infinite loop construct:
|
|
|
|
```mist
|
|
loop {
|
|
println!("forever");
|
|
if (done) break;
|
|
}
|
|
```
|
|
|
|
### For-In Loop
|
|
|
|
For loops iterate over an expression using the `pattern : expr` syntax:
|
|
|
|
```mist
|
|
for (i : 0..4) {
|
|
sum += i;
|
|
}
|
|
|
|
// With pattern destructuring
|
|
for ([k, _] : pairs) {
|
|
keys += k;
|
|
}
|
|
```
|
|
|
|
### While Loop
|
|
|
|
```mist
|
|
while (count < 5) {
|
|
count++;
|
|
}
|
|
|
|
while (active) {
|
|
wait_for_event();
|
|
}
|
|
```
|
|
|
|
## Jump Statements
|
|
|
|
- **`return`**: Exits the current function, optionally passing back a value.
|
|
- **`break`**: Terminates the innermost looping construct.
|
|
- **`continue`**: Skips the remainder of the current loop iteration.
|
|
|
|
## Key Characteristics
|
|
|
|
- **Statement Bodies**: If, while, for, and loop branches can omit braces for single statements or expressions.
|
|
- **Implicit Returns**: Expression bodies (without `;`) implicitly return their value.
|
|
- **Pattern Integration**: Loops and match arms utilize Mist's pattern system for data destructuring.
|
|
- **Multiple Patterns**: Match arms support `|` for matching multiple patterns.
|