106 lines
2.4 KiB
Plaintext
106 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 — meaning braces can be omitted for single-statement branches.
|
|
|
|
## Conditionals
|
|
|
|
The `if` statement evaluates a boolean expression. Single-statement bodies don't need braces:
|
|
|
|
```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 (soft return)
|
|
var 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");
|
|
}
|
|
}
|
|
```
|
|
|
|
## Loops
|
|
|
|
### Loop
|
|
|
|
An infinite loop construct:
|
|
|
|
```mist
|
|
loop {
|
|
println!("forever");
|
|
if (done) break;
|
|
}
|
|
```
|
|
|
|
### C-Style For Loop
|
|
|
|
```mist
|
|
for (var mut i = 0; i < 10; i++;)
|
|
println!("Index: {}", i);
|
|
```
|
|
|
|
### For-In Loop
|
|
|
|
```mist
|
|
for (var item in collection)
|
|
process(item);
|
|
|
|
for ((i32 x, i32 y) in coordinates)
|
|
draw_point(x, y);
|
|
|
|
// Range iteration
|
|
for (var i in 0..10)
|
|
println!("{}", i);
|
|
```
|
|
|
|
### While Loop
|
|
|
|
```mist
|
|
while (active) {
|
|
wait_for_event();
|
|
}
|
|
|
|
while (count > 0) process(count--);
|
|
```
|
|
|
|
## 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.
|
|
- **Soft 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.
|