Control Flow
Every program needs to make decisions and repeat actions. Control flow is how we express that logic—and Coco aims to make it both powerful and readable.
What's in This Chapter
We'll cover the fundamental building blocks:
- Conditionals — The classic if/else, but as expressions
- Pattern Matching — Match expressions that are exhaustive and expressive
- Loops — For and while loops with clean syntax
- Iterators — Functional-style chains for transforming data
Design Philosophy
Coco's control flow follows a few key principles:
Everything is an expression. If statements and match expressions return values. No need for ternary operators or awkward workarounds.
Exhaustiveness matters. When you match on an enum or Result, the compiler ensures you handle every case. No more forgotten error paths.
Clarity over cleverness. We don't have five ways to do the same thing. Each construct has a clear purpose and obvious syntax.
Composition over mutation. Iterator chains let you express complex transformations without mutable state scattered everywhere.
Quick Examples
// If as an expression
$status = if $logged_in { "Welcome back" } else { "Please sign in" };
// Pattern matching
match $result {
Ok($value) => process($value),
Err($e) => log_error($e)
}
// Clean loops
for $item in $items {
echo $item;
}
// Iterator chains
$total = $orders
.iter()
.filter(($o) { $o.status == "completed" })
.map(($o) { $o.amount })
.sum();
Let's dive into each of these.
Pages in this chapter:
- Conditionals — If/else expressions and boolean logic in Coco
- Pattern Matching — Match expressions, exhaustiveness, and destructuring in Coco
- Loops — For and while loops, ranges, and loop control in Coco
- Iterators — Iterator chains, lazy evaluation, and functional-style data transformation