Files
mist-website/content/docs/logic/control-flow.mdx
T
2026-06-28 22:45:01 +02:00

116 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. Conditions do not require parentheses, and blocks support expression bodies.
## Conditionals
The `if` statement evaluates a boolean expression without parentheses:
```mist
if score > 50 {
println!("Pass");
} else if score == 50 {
println!("Borderline");
} else {
println!("Fail");
}
// 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 `for pattern in expr` syntax:
```mist
for i in 0 .. 4 {
sum += i;
}
// With pattern destructuring
for (k, _) in pairs {
keys += k;
}
// With range variable
let r = 0 .. 5;
for i in r {
count++;
}
```
### 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
- **No Parentheses**: Conditions in `if`, `while`, and `match` do not require parentheses.
- **Implicit Returns**: Expression bodies 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.
- **Expression `if`**: `if/else` blocks can be used as expressions.